簡體   English   中英

在結構內分配結構的動態數組

[英]Allocating dynamic array of structures within a structure

我有以下結構:

struct date {
    int year;
    int month;
    int day;
};

struct person{
    char name[64];
    struct date birthday;
};

struct aop {
    int max;
    struct person **data;
};  

我嘗試使用malloc在aop結構中獲取數據,如下所示:(此處未發生錯誤)

struct aop *create_aop(int max) {
    struct aop *s = malloc(sizeof(struct aop));
    s->max = max;
    s->data = malloc((sizeof(struct person)) * max);
    return s;
}  

但是,當我嘗試訪問代碼其他部分中的“數據”時,例如:

a->data[len]->birthday.year = birthday.year;  

我有錯誤。
我是用錯誤的方式分配malloc,還是不正確地訪問數據?

先感謝您!

在aop結構中,結構人不需要雙指針。 所以

struct aop {
    int max;
    struct person **data;
};  

更改struct person **data;

struct person *data;

並在使用時按以下方式使用它。

a->data[len].birthday.year = birthday.year;  

aop結構中的字段數據是Poiters數組,因此首先需要為指針分配內存:

s->data = malloc((sizeof(struct person*)) * max);

然后在循環中,您需要為每個結構分配內存:

for(i = 0; i < max; i++) {
    s->data[i] = malloc(sizeof(struct person));
}

我試圖在這里創建相同的結構,但無法訪問該結構Person。

由於您願意創建多人條目,因此如何創建鏈接列表? 喜歡:

struct aop {
  int max;
  struct person **data;
};
struct person{
  char name[64];
  struct date birthday;
  struct person *nextPerson;
};

可能會起作用。

我是用錯誤的方式分配malloc,還是不正確地訪問數據?

是。 研究這個令人難以置信的信息圖表:

Type *****var = malloc (sizeof(Type****) * n_items);
/*   -----                         ----                   */
/*     |                             |                    */
/*     +---> n stars                 +---> n-1 stars      */

如果您有一顆以上的星星,則說明您還沒有完成。 您需要在下一個間接級別分配數據:

for (i = 0; i < n_items; ++i)
{
   var[i] = malloc (sizeof(Type***) * n_items_level2);
   /*                          ---                        */
   /*                           |                         */
   /*                           +---> n-2 stars           */

如果您仍然有星星,那么您還沒有完成。 您需要在嵌套循環的下一個間接級別分配數據:

   for (j = 0; j < n_items_level2; ++j)
   {
       var[i][j] = malloc (sizeof(Type**) * n_items_level3);

以此類推,直到星星耗盡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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