繁体   English   中英

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

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

我有以下 C struct

typedef struct {

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

在我的代码中有一点,我必须为struct的最后一个变量( followers )分配内存,但我遇到了问题。

我试过这个:

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

或这个

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

但我编译后得到的输出如下:

错误:灵活数组成员的无效使用

我怎样才能正确地做到这一点?

编辑

我的 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 != '#') {
              ...
          }
      }
  }

正如 tadman 所提到的,而不是char *followers[]; 使用char **followers; 声明该字段。

还要注意 malloc 不会初始化内存(尽管在 linux 上,如果未重用,内存可能会初始化为 0),因此您使用 realloc 可能会导致堆损坏。 相反,只需再次使用 malloc (或使用 calloc 分配结构)。

暂无
暂无

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

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