简体   繁体   中英

How to dynamically allocate memory to a array of array in C?

I have the following 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.

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:

 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[]; use 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. Instead, just use malloc again (or use calloc to allocate the struct).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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