I don’t quite understand how pointers work with C arrays. Here’s some code I got:
int arrayOne[] = {1, 2, 3};
int arrayTwo[] = {4, 5, 6, 7};
int **arrayThree = (int **)malloc(2 * sizeof(int));
arrayThree[0] = arrayOne;
arrayThree[1] = arrayTwo;
for (int i = 0; i < 2; i++) {
int *array = arrayThree[i];
int length = sizeof(array) / sizeof(int);
for (int j = 0; j < length; j++)
printf("arrayThree[%d][%d] = %d\n", i, j, array[j]);
}
I would have expected this to output the following:
arrayThree[0][0] = 1
arrayThree[0][1] = 2
arrayThree[0][2] = 3
arrayThree[1][0] = 4
arrayThree[1][1] = 5
arrayThree[1][2] = 6
arrayThree[1][3] = 7
What it actually prints out is:
arrayThree[0][0] = 1
arrayThree[0][1] = 2
arrayThree[1][0] = 4
arrayThree[1][1] = 5
Why?!
sizeof(array)is the size of a pointer, which just happens to be the twice the size of aninton your platform.There’s no way to get the length of an array in C. You just have to remember it yourself.