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;
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--;
}
}