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?
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.
*ret and lazy.