0

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 " (?) " ?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Hannodje
  • 11
  • 3
  • `struct foo**`? An array is still a pointer... – hlt Dec 01 '15 at 17:59
  • 1
    [No need to cast the results of `malloc` and `calloc`.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc?rq=1) – tonysdg Dec 01 '15 at 18:01
  • Also - I believe (could be wrong) that `sizeof *array_of_pointers` is preferable, but that may be stylistic. – tonysdg Dec 01 '15 at 18:03

1 Answers1

3

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.

nnn
  • 3,980
  • 1
  • 13
  • 17