Question

I want to print my doubly linked list. Here is the function

void show(que *q) {
    que *temp;
    temp = q;

    if (q->cnt == 0)
        printf ("\nEmpty.\n");
    else {
        while (temp->cnt > 0) {
            printf("%d[prioriy=%d]  cnt:%d\n", temp->fr->dat, temp->fr->priority);
            temp->fr = temp->fr->prv;
            temp->cnt--;
        }
    }
}

I assign struct element q to other element temp, and only modify temp, but why does the value of q also change? For example q->cnt becomes equal to zero, despite that I didn't modify it.

EDIT:

typedef int kintyr;

typedef struct qElem {
    struct qElem *prv;          
    kintyr *dat;                    
    int *priority;
} qElem;


typedef struct que {
    qElem *fr, *bk;             
    int cnt;                    
} que;
Was it helpful?

Solution

q and temp are both pointers, that is, they store addresses in memory. By modifying data that one of them points to, retrieving that data via the other pointer will reflect those changes because they both point to the same location in memory. The data itself is only stored in one place.

If you want to iterate over your list, you'll want a temporary pointer to a node, which you'll walk through the list using a local counter (instead of modifying the one in the list):

//Set a temporary node to point to the front of the queue
qElem *temp = q->fr;
//Create a local variable to track where in the queue we are
int cnt = q->cnt;
if(cnt==0)
    printf ("\nEmpty.\n");
else
{
    while(cnt>0)
    {
        printf( "%d[prioriy=%d]  cnt:%d\n", temp->dat, temp->priority );
        //Point to the next node in the queue
        temp = temp->prv;
        //Decrement our local counter
        cnt--;
    }

}

OTHER TIPS

  1. temp is also pointing to the memory of the q, change in the value of temp->cnt-- is same as the q->cnt--
  2. Better you take the int count = q->cnt , operate on the count variable

q is an address to memory. You say that temp shall be an address to memory as well. This is due to *. When you assign temp = q you say that the address of temp shall go to the same address as q in memory. If you want a new que var don't use * before temp.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top