To allocate an array of foo_t
s, the standard pattern is one of these:
foo_t *p = malloc(count * sizeof(foo_t));
foo_t *p = malloc(count * sizeof(*p));
You either say "give me count items of size s", where the size is either sizeof(foo_t)
or sizeof(*p)
. They're equivalent, but the second is better since it avoids writing foo_t
twice. (That way, if you change foo *p
to bar *p
you don't have remember to change sizeof(foo_t)
to sizeof(bar_t)
.)
So, to allocate an array of int *
, replace foo_t
with int *
, yielding:
int **p = malloc(count * sizeof(int *));
int **p = malloc(count * sizeof(*p));
Notice that the correct size is sizeof(int *)
, not sizeof(int **)
. Two stars is too many. The first snippet where you wrote sizeof(int **)
is, therefore, wrong. It appears to work, but that's just luck.
Notice also that I did not include an (int **)
cast. The cast will work, but it's a bad idea to cast the return value of malloc()
. The cast is unnecessary and could hide a subtle error*. See the linked question for a full explanation.
* Namely, forgetting to #include <stdlib.h>
.