簡體   English   中英

具有指向結構節點的指針的動態數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM