Pointers are not arrays and arrays are not pointers. A pointer can however be used to point at the first element in an array.
You need to make up your mind if you wish to have a 2D array of int
or a 1D array of int*
, each pointing the first element of an array.
A 2D array is simply:
int arr[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
This is the fastest form you'll ever get, but it is restricted to the scope it is allocated inside.
A 1D array of pointers to first elements can be done by having the pointers point at local scope arrays:
int* arr [3] = {(int[]){1,2,3,4}, (int[]){5,6,7,8}, (int[]){9,10,11,12}};
This is utilizing the feature known as compound literals. These arrays will have the same scope as arr
and go out of bounds when arr
does.
If you need the arrays to stay alive outside that scope, you could use dynamic memory allocation instead:
int (*arr)[4] = malloc( sizeof(int[3][4]) );
...
arr[i][j] = something;
...
free(arr);
The above creates a dynamically allocated 2D array, then lets an array pointer point at the first array inside that 2D array.
It's also possible to create slower, crappier code by dynamically allocating a 1D array of int*
then have each pointer point at the first element of an array:
int** arr = malloc( sizeof(int*[3]) );
for(size_t i=0; i<3; i++)
{
arr[i] = malloc( sizeof(int[4]) );
}
...
for(size_t i=0; i<3; i++)
{
free(arr[i]);
}
free(arr);
This amateur form has absolutely no advantage in your case. Code like the above only makes sense when we need completely variable-sized dimensions, which we don't in case of static 2D arrays.
So all this version does is to segment the heap and block data cache utilization, wasting memory and execution speed. You also need to free() it in several steps, with a loop.
More info: Correctly allocating multi-dimensional arrays