简体   繁体   中英

Error with malloc while creating memory for list of struct pointers

For some reason, while trying to create an array of pointers of a struct called Node , I keep getting an error:

Node ret[2] = (struct Node*)malloc(2*sizeof(Node));
error: invalid initializer

Can someone please help me with that?

Node ret[2] = (struct Node*)malloc(2*sizeof(Node));

should probably be:

Node *ret = malloc(2 * sizeof(*ret));

That's because you need a pointer to the memory, not an array. With an array, it's initialisation, which would require a braced init list. Note that this only provides memory for the pointers, not the things they point at - they need to be allocated separately if you wish to use them.

You'll probably notice two other changes as well:

  • I've removed the cast on the malloc return value. This serves no purpose in C since the void* returned can be implicitly cast to other pointer types. In fact, there are situations where explicit casts can lead to subtle problems.

  • I've used *ret as the variable to get the size rather than the type. This is just habit of mine so that, if I change the type to (for example) tNode , I only have to change it in one place on that line - yes, I'm basically lazy :-) Note that this is just a preference, doing it the original way has no adverse effect on the program itself, just developer maintenance.

I think your struct is typedef ed

Node ret[2]  = ( struct Node* ) malloc( 2 * sizeof(Node) );

it should be

Node *rec[2] = { malloc(sizeof(Node)) , malloc(sizeof(Node)) };

or

Node *rec    =  malloc(2*sizeof(Node));    

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