【问题标题】:dynamic array with pointers to struct nodes带有指向结构节点的指针的动态数组
【发布时间】: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


    【解决方案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 *));
    

    您使用realloc() 为下一个元素添加空间,但是在nodeT-&gt;table_size++ 之后,nodeT-&gt;table-&gt;size 的值是下一个元素的 索引,因为 C 数组索引为零-基于,所以元素的数量应该是nodeT-&gt;table_size + 1

    这是一个典型的off-by-one error

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2021-02-19
      • 1970-01-01
      • 2018-09-20
      • 2020-05-10
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      相关资源
      最近更新 更多