This is sample code my teacher showed us about \"How to dynamically allocate an array in C?\". But I don\'t fully understand this. Here is the code:
int k;
i
Yes indeed, int**
is a pointer to a pointer. We can also say it is an array of pointers.
test = (int **) malloc(k * sizeof(int*));
This will allocate an array of k
pointers first. malloc
dynamically allocates memory.
test[i] = (int*) malloc(k * sizeof(int));
This is not necessary as it is enough to
test[i] = (int*) malloc(sizeof(int*));
Here we allocate each of the array places to point to a valid memory. However for base types like int
this kind of allocation makes no sense. It is usefull for larger types (structs).
Each pointer can be accessed like an array and vice versa for example following is equivalent.
int a;
test[i] = &a;
(test + i) = &a;
This could be array test
in memory that is allocated beginning at offset 0x10000000:
+------------+------------+ | OFFSET | POINTER | +------------+------------+ | 0x10000000 | 0x20000000 | test[0] +------------+------------+ | 0x10000004 | 0x30000000 | test[1] +------------+------------+ | ... | ...
Each element (in this example 0x2000000 and 0x30000000) are pointers to another allocated memory.
+------------+------------+ | OFFSET | VALUE | +------------+------------+ | 0x20000000 | 0x00000001 | *(test[0]) = 1 +------------+------------+ | ... +------------+------------+ | 0x30000000 | 0x00000002 | *(test[1]) = 2 +------------+------------+ | ...
Each of the values contains space for sizeof(int) only.
In this example, test[0][0]
would be equivalent to *(test[0])
, however test[0][1]
would not be valid since it would access memory that was not allocted.