0

If i have a list of lists as

typedef Struct b {
int b;
Struct b *next;
}B;

typedef Struct a {
int a;
Struct a *next;
B *link;
}A;

and if i develop the data structure following this scheme.. enter image description here

I use a double pointer as head for B for keep track of all the nodes of B between the A nodes. So if i use realloc to give more data to the pointer, i will not lose previously allocated data inside the head, right ?

for(i=0;i<n_of_B_lists;i++)
  *head_b[i]=realloc(*head_b[i],sizeof(B *)*1); //1 is for 1 pointer to the new B list
Luca
  • 55
  • 7
  • 2
    [Be careful with your operator precedence](http://en.cppreference.com/w/c/language/operator_precedence) – WhozCraig Jan 04 '15 at 21:07
  • @WhozCraig I'ts wiered that I used the same words that you used, without seeing your comment, and when you commented it was not in my answer, when I was writing the example of a better usage of `realloc`, I noticed that the OP may not know the difference between `(*head_b)[i]` and `*(head_b[i])`. – Iharob Al Asimi Jan 04 '15 at 21:11
  • It appears odd to see `[]` used in code using linked-lists. – chux - Reinstate Monica Jan 04 '15 at 22:22
  • why ? i'm still a beginner ;) – Luca Jan 04 '15 at 22:31

1 Answers1

1

Yes that's what realloc is exactly for, though I would recommend a different way of using it, just

void *temp;

temp = realloc(*head_b[i], sizeof(B *));
if (temp == NULL)
    doSomethingReallocFailed();
*head_b[i] = temp;

also be careful with operator precedence in the *head_b[i] expression.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97