0

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?

1
  • You are returning a struct Node pointer. Use Node *ret = ..., it will point to the first element of the array Commented Mar 31, 2020 at 2:34

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

UV for *ret and lazy.
1

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));    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.