【发布时间】:2014-01-05 13:59:21
【问题描述】:
我在使用 C 语言的一些代码时遇到了问题,我真的需要你的帮助。好吧,我有这 2 个结构(要求它们是这样的,所以我们不能更改它们)
struct node{
struct list_node **table;
int table_size;
};
struct list_node{
int num;
struct list_node *ptr;
};
正如你在第一个中看到的,我们有一个数组,在我们列表的节点中有指针。在 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 行,这对我没有帮助。我希望你会,这就是我发布这个的原因。提前致谢!
【问题讨论】:
标签: c arrays pointers struct dynamic-data