You could do this:
int** num_list_1 = malloc(10*sizeof(int*));
for(int i=0; i<10; i++) {
num_list_1[i] = malloc(sizeof int);
num_list_1[i][0] = atoi("1234");
}
for(int i=0; i<10; i++) {
free(num_list_1[i]);
}
free(num_list_1);
Or you could do this:
int** num_list_2 = malloc(10*sizeof(int*));
num_list_2[0] = malloc(10*sizeof(int));
for(int i=1; i<10; i++) {
num_list_2[i] = NULL;
}
for(int i=0; i<10; i++) {
num_list_2[0][i] = atoi("1234");
}
Notice that in the first example the key assignment is
num_list_1[i][0] = atoi("1234");
while in the second example it is
num_list_2[0][i] = atoi("1234");
Another way to write the first (not the second) example would be
*num_list_1[i] = atoi("1234");
The first example looks like this in memory:
+---+
num_list_1: | * |
+-|-+
|
v
+---+ +------+
| *----> | 1234 |
+---+ +------+ +------+
| *-----------------> | 1234 |
+---+ +------+ +------+
| *----> | 1234 |
+---+ +------+
.
.
.
+---+ +------+
| *----> | 1234 |
+---+ +------+
The second example looks like this:
+---+
num_list_2: | * |
+-|-+
|
v
+---+ +------+------+------+ +------+
| *----> | 1234 | 1234 | 1234 | ... | 1234 |
+---+ +------+------+------+ +------+
| 0 |
+---+
| 0 |
+---+
.
.
.
+---+
| 0 |
+---+
Notice that in each case, num_list_1
and num_list_2
point to an array of pointers, and each of those second-level pointers actually points to an int
(or to several int
s in the case of num_list_2
).
If you could use int *
(as in SlLoWre's answer) it would look like this:
+---+ +------+------+------+ +------+
num_list: | *----> | 1234 | 1234 | 1234 | ... | 1234 |
+---+ +------+------+------+ +------+
But, again, if you want this picture, num_list
has to be an int *
, not an int **
.
The requirement to use int **
seems strange. The only reason I can imagine that you would use an int **
would be if you are using a function to construct the array, and the function is returning the pointer by reference. That would look like this:
void allocate_array(int **num_list_p)
{
*num_list_p = malloc(10*sizeof(int*));
for(int i=0; i<10; i++) {
(*num_list_p)[i] = atoi("1234");
}
}
int main()
{
int *num_list;
allocate_array(&num_list);
for(int i = 0; i < 10; i++) {
printf("%d: %d\n", i, num_list[i]);
}
}
Also, one last thing: You probably knew this, but in real code, we would always check the return value of malloc
to make sure it wasn't NULL
.