Watching some code found on internet I came across this piece of code:
int (*p)[3];
p = (int(*)[3]) calloc(5*3,sizeof(int));
is it just a way to alloc a matrix?
I understand that int (*p)[3] creates a pointer to an array of 3 int, but I’m not sure about the calloc call: I know that calloc allocate and initialize a number of int (in this case) equal to the first parameter (5*3).
Thus, if I assign it to p it should mean that the pointer now points to the just allocated memory location.
So, since I know my reasoning is wrong, may somebody correct me?
You’re true that this is a pointer to an array of three ints, but this pointer could also point to the beginning of an array of arrays of three ints.
Here, you allocate 5 * 3 ints to this pointer. As
int[3]has 3 ints, you just allocated 5 suchint[3]arrays.You may then refer to these
int[3]arrays asp[0]…p[4]so you get a two-dimensional array ranging
p[0][0]…p[0][2]p[4][0]…p[4][2]