在结构内分配动态结构数组

时间:2014-11-17 11:47:34

标签: c arrays struct

我有以下结构:

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,还是我错误地访问了数据?

提前谢谢!

4 个答案:

答案 0 :(得分:3)

在aop结构中,你不需要结构人的双指针。所以

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

更改struct person **data;

struct person *data;

使用时请按以下方式使用。

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

答案 1 :(得分:0)

aop结构中的字段数据是poiters数组,所以首先需要为指针分配内存:

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

然后在循环中,您需要为每个结构分配内存:

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

答案 2 :(得分:0)

我试图在这里创建相同的结构,我无法进行结构Person。

既然您愿意创建多人条目,那么创建链表怎么样? 像:

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

可能它会起作用。

答案 3 :(得分:0)

  

我是以错误的方式做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);

等等,直到你没有星星。