Although necessary in C++, it is not necessary (nor suggested) to cast the return of [m][c][re]alloc
in ANSI C. So your first statement should be: (note the argument of the sizeof
statement...)
list = malloc(sizeof(* list) * numberOfRows);//create the first level of array of pointers
Then loop through, as you have indicated in your post, allocating memory for each of the locations created in the first statement:
for(i=0;i<numOfRows;i++)
{
list[i] = malloc(sizeof(int));
}
Note: in acknowledgement of @M.M's comment, although it is not necessary, or generally recommended (read link above) to cast return of malloc in C, the example code you provide in your original post provides one good illustration where using the cast spotlights and exposes immediately the possibility of a bug. i.e. that the cast: (int **)
does not match the argument of sizeof
: int
.