简体   繁体   中英

Can not declare array of pointers to struct inside struct in C

I want to have an array inside struct which will store pointers of same data-type (ie struct map ). I looked on Stackoverflow and found this:

struct map {
    int city;
    struct map **link = (struct map *)malloc(204800 * sizeof(struct map *));
}

But I am getting this error:-

error: expected ':', ',', ';', '}' or '__attribute__' before '=' token    
    struct map **link = (struct map *)malloc(204800*sizeof(struct map *));

This is a struct definition, you cannot malloc or use any function inside a declaration, because the declaration does not get executed, it is merely a kind of template on how a struct of type 'map' should look like, that way the compiler will know how much memory should be allocated to struct map when we create an instance of it.

when you want to use members inside struct map(for example make the pointer link point to some viable memory segment) you need to create an instance of 'map' somewhere, and only then you will be able to call malloc and make link point to the resulting memory segment.

the way to fix this is first declare the struct like so:

struct map{
int city;
struct map **link;
};

and when you create an instance of the struct in main, you can allocate space for link like so:

int main()
{
   struct map *temp = malloc(sizeof(struct map));
   temp->link = malloc(204800*sizeof(struct map *));
   return 0;
}

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