I'm using gcc version 4.8.0 with flags -Wall -std=gnu99
.
I need to dynamically allocate the memory for a contiguous 2D array using malloc in C; this fact is nonnegotiable. However, for ease of use I still want to be able to access the array using the convenient x[r][c]
notation. Here's my valiant attempt at creating a pointer to a contiguous 2D array and indexing the array by doing *array[r][c]
:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
size_t rows = 3, cols = 5;
printf("sizeof(int) = %li\n\n", sizeof(int));
int (*array)[rows][cols] = malloc(sizeof(int) * rows * cols);
printf("array starts at %p\n", array);
printf("sizeof(array) = %li\n", sizeof(array));
printf("sizeof(array[0][0]) = 0x%lx\n", sizeof(array[0][0]));
puts("");
unsigned short r, c;
for (r = 0; r <= rows - 1; r++) {
for (c = 0; c <= cols - 1; c++) {
printf("array[%i][%i] is at %p\n", r, c, &(*array[r][c]));
};
puts("");
};
}
Although it compiles without warnings, it has some unexpected output:
sizeof(int) = 4
array starts at 0x16cc010
sizeof(array) = 8
sizeof(array[0][0]) = 0x14
array[0][0] is at 0x16cc010
array[0][1] is at 0x16cc024
array[0][2] is at 0x16cc038
array[0][3] is at 0x16cc04c
array[0][4] is at 0x16cc060
array[1][0] is at 0x16cc04c
array[1][1] is at 0x16cc060
array[1][2] is at 0x16cc074
array[1][3] is at 0x16cc088
array[1][4] is at 0x16cc09c
array[2][0] is at 0x16cc088
array[2][1] is at 0x16cc09c
array[2][2] is at 0x16cc0b0
array[2][3] is at 0x16cc0c4
array[2][4] is at 0x16cc0d8
I don't really understand what's happening here. The elements are contiguous, but they're way too large for ints, and the array is way too small to hold all of them.
My array declaration is the part I'm most unsure about — I'm reading int (*array)[rows][cols]
as "array
is a pointer to an array (with stride cols
) of ints", but apparently that's incorrect.
What exactly am I doing wrong here?