Hannodje
Hannodje

Reputation: 11

Casting to array of pointers in C99

I'm currently writing a complex function that took me a great amount of time to conceive. This function uses an array of type: " struct foo* ", which was previously defined like this:

struct foo** array_of_pointers = NULL;

To make the code easier to understand, I decided to change the definition to:

struct foo* array_of_pointers[] = {NULL};

(The assignment is done to make it a strong symbol)

But now the problem is here:

array_of_pointers = (?) calloc(256, sizeof(struct foo*));

Intuitively I replaced " ? " with " struct foo* [ ] ". This looks weird and actually results in a compiler error: "cast specifies array type".

So my question is: Does anyone know what should be placed instead of " (?) " ?

Upvotes: 0

Views: 442

Answers (1)

nnn
nnn

Reputation: 4220

Here you are declaring an array of type struct foo* with a single element (because on unspecified size []), and that element is NULL:

struct foo* array_of_pointers[] = {NULL};

The address it points to can't be changed, as in:

array_of_pointers = calloc(256, sizeof(struct foo*));  
// wrong, doesn't compile and casting the return of calloc won't help

It is not the same as when declaring a pointer to struct foo* , as here:

struct foo** array_of_pointers = NULL;

You can only assign to the latter.

Upvotes: 3

Related Questions