C 带有指向结构节点指针的动态数组
我在C语言中遇到了一些问题,我真的需要你的帮助。我有这两个结构(它们被要求像这样,所以我们不能改变它们) 正如您在第一个列表中看到的,我们有一个数组,在列表的节点中有指针。大体上,我们创建所需的内存空间,这样开始C 带有指向结构节点指针的动态数组,c,arrays,pointers,struct,dynamic-data,C,Arrays,Pointers,Struct,Dynamic Data,我在C语言中遇到了一些问题,我真的需要你的帮助。我有这两个结构(它们被要求像这样,所以我们不能改变它们) 正如您在第一个列表中看到的,我们有一个数组,在列表的节点中有指针。大体上,我们创建所需的内存空间,这样开始 struct node *nodeT; struct list_node *root, *curr, **temp; root = (struct list_node*)malloc(sizeof(struct list_node)); // root node of l
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;
}
我使用这个struct list_node**temp来保护节点集的安全,检查后,如果一切正常,我会再次将temp放入节点集,否则我会停止程序。最后,我通过数组指针打印列表的内容,如下所示
for(i=0 ; i<nodeT->table_size ; i++)
printf("-> %d ", nodeT->table[i]->num);
printf("\n");
for(i=0;i表大小;i++)
printf(“->%d”,节点->表[i]->num);
printf(“\n”);
然后我退出程序。这其中的悖论是,对于x1-4,一切都很好,但是对于5+有一个问题,我得到了一个信息
“**检测到glibc*。/dynamix\u table\u 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
的值是下一个元素的索引,因为C数组索引是零基的,所以元素的数量应该是nodeT->table_size+1
这是一个典型的例子
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 *));