列表以头为双指针

时间:2015-01-04 20:59:11

标签: c list realloc double-pointer

如果我有一个列表列表为

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

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

如果我按照这个方案开发数据结构.. enter image description here

我使用双指针作为B的头,用于跟踪A节点之间B的所有节点。 因此,如果我使用realloc为指针提供更多数据,我不会丢失先前在头部分配的数据,对吗?

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

1 个答案:

答案 0 :(得分:1)

是的,realloc究竟是什么,不过我建议使用不同的方法,只需

void *temp;

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

还要注意*head_b[i]表达式中的运算符优先级。