Search code examples
ccircular-list

Nodes in circular list having the same value


I have the following code:(courtesy to Armin )

 int InsForward (TL2 p, void* x){
 /* Inserta a node a step forward from the supplied p*/
 TL2 h = (TL2)calloc(1,sizeof(TCel2));
 if (!h)
    return 0;
h->pre = p;        //sets h previous to point to p
h->nxt= p->nxt;    //sets h next to point to where p was pointing ( sentinel )
p->nxt->prv = h;   //sets the sentinel previous to point to h
p->nxt = h;        //sets the p next to point to h
h->info = x;   
return 1;

What I tried:

/* TCel a, int p, FILE fi*/
while(fscanf(fi,"%i%i", &(p.x), &(p.y)) == 2)
 if ( InsForward(a, &p) == 0)   
   break;    

The struct:

typedef struct cel2
{ 
  struct cel2 *pre, *nxt;  
 void* info;              
} TCel2, *TL2;

So I checked it:

 /* TL2 u*/

 for (u = a->nxt; u != a; u = u->nxt)
   printf("%p \n",  u->info);

Yes, the info is void, but I was curious if the addresses were different...I suppose no:

 0028FEA8 0028FEA8 0028FEA8 0028FEA8 0028FEA8 0028FEA8 

Why are they the same?!


Solution

  • In this loop, you are never creating a new p. You are reusing the same p to store the results of fscanf, and then using a pointer to p to set the info field of your nodes.

    while(fscanf(fi,"%i%i", &(p.x), &(p.y)) == 2)
     if ( InsForward(a, &p) == 0)   
       break;
    

    That's why all the pointers end up pointing to that same p. This would not be what you want, because:

    1. All your nodes will be pointing to the same p as their info.
    2. Since you are creating a dynamic # of these nodes, you should allocate these info structs on the heap with malloc, calloc, etc.

    I assume p is a struct with an x and y field, both of which are ints. You should so something like this instead. I'll call this struct tuple_t.

    while(true) {
     tuple_t *p = malloc(sizeof(tuple_t));
     int f = fscanf(fi,"%i%i", &(p->x), &(p->y));
     if (f != 2 || InsForward(a, p) == 0) {
       break;
    }
    

    Of course, you'll need to add more error handling and memory management as you see fit.