简体   繁体   English

如何在C中为数组数组动态分配内存?

[英]How to dynamically allocate memory to a array of array in C?

I have the following C struct :我有以下 C struct

typedef struct {

    char *name;
    int nfollowers;
    char *followers[];
} User;

There's a point in my code where I have to allocate memory for the last variable of the struct ( followers ) and I'm having issues on it.在我的代码中有一点,我必须为struct的最后一个变量( followers )分配内存,但我遇到了问题。

I have tried this:我试过这个:

users[nusers].followers = (char **) realloc(users[nusers].followers, sizeof(char));

or this或这个

users[nusers].followers = (char **) realloc(users[nusers].followers, sizeof(char *));

but the output I get after compiling is the following:但我编译后得到的输出如下:

error: invalid use of flexible array member错误:灵活数组成员的无效使用

How can I properly do this?我怎样才能正确地做到这一点?

EDIT编辑

Example of how my C file is structured:我的 C 文件的结构示例:

 User *users;
 int i=0, n, nusers=0;
 char aux, *str;
 
 fd_in = open(argv[1], O_RDONLY);
 
 if (fd_in >= 0) {

    users = (User *) malloc(sizeof(User));

    while (aux!='&') {

        users[nusers].followers = (char **) realloc(users[nusers].followers, sizeof(char)); //Issue

          while (aux != '#') {
              ...
          }
      }
  }

As mentioned by tadman, instead of char *followers[];正如 tadman 所提到的,而不是char *followers[]; use char **followers;使用char **followers; to declare the field.声明该字段。

Also watch out that malloc does not initialize memory (though on linux the memory might be initialized to 0 if it has not been reused) so your use of realloc may result in corrupting the heap.还要注意 malloc 不会初始化内存(尽管在 linux 上,如果未重用,内存可能会初始化为 0),因此您使用 realloc 可能会导致堆损坏。 Instead, just use malloc again (or use calloc to allocate the struct).相反,只需再次使用 malloc (或使用 calloc 分配结构)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM