[英]dynamic array with pointers to struct nodes
我在C语言中遇到一些麻烦,我真的需要您的帮助。 好吧,我有这两个结构(要求它们像这样,所以我们不能更改它们)
struct node{
struct list_node **table;
int table_size;
};
struct list_node{
int num;
struct list_node *ptr;
};
正如您在第一个中看到的那样,我们有一个array,在列表的节点中有指针。 在main中,我们创建所需的内存空间来像这样开始
struct node *nodeT;
struct list_node *root, *curr, **temp;
root = (struct list_node*)malloc(sizeof(struct list_node)); // root node of list
nodeT = (struct node*)malloc(sizeof(struct node)); // single node
nodeT->table = (struct list_node**)malloc(sizeof(struct list_node*));
nodeT->table_size = 0;
然后创建列表
for(i=0 ; i<X ; i++){ // X is important for the errors and i'll explain why
curr = (struct list_node*)malloc(sizeof(struct list_node));
curr -> num = (i+1);
curr -> ptr = root;
root = curr;
}
现在,我遍历列表,并在找到的每个列表节点的第一个结构中扩展数组,以输入指向正确节点的指针。
for(curr=root ; curr!=NULL ; curr=curr->ptr){
nodeT->table[nodeT->table_size] = curr;
nodeT->table_size++;
temp = (struct list_node**)realloc(nodeT->table , nodeT->table_size*sizeof(struct list_node *));
if(temp!=NULL)
nodeT->table = temp;
else{
printf("Memory error\n");
return 1;
}
}
我使用此struct list_node ** temp来保持安全的nodeT,并在检查完之后,如果一切正常,请再次将temp放入nodeT,否则停止程序。 最后,我像这样通过数组的指针打印列表的内容
for(i=0 ; i<nodeT->table_size ; i++)
printf("-> %d ", nodeT->table[i]->num);
printf("\n");
我退出程序。 矛盾的是,对于X 1-4,一切正常,但是对于5+,有问题,我得到一条消息
“ **检测到glibc * ./dynamix_table_realloc:realloc():无效的下一个大小:0x0000000000819050 * ”
大约还有20条线,对我没有帮助。 希望您会这样,这就是为什么我发布了此内容。 提前致谢!
您在此处未分配足够的内存:
temp = (struct list_node**)realloc(nodeT->table , nodeT->table_size*sizeof(struct list_node *));
它应该是:
temp = (struct list_node**)realloc(nodeT->table , (nodeT->table_size+1)*sizeof(struct list_node *));
您使用realloc()
为下一个元素添加空间,但是在nodeT->table_size++
之后, nodeT->table_size++
nodeT->table->size
的值是下一个元素的索引 ,因为C数组的索引是从零开始的,所以数字元素的数量应为nodeT->table_size + 1
。
这是一个典型的一次性错误 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.