C - dynamic arrays

I don’t quite understand how pointers work with C arrays. Here is the 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 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

It actually prints:

arrayThree[0][0] = 1
arrayThree[0][1] = 2
arrayThree[1][0] = 4
arrayThree[1][1] = 5

Why?

+3
source share
4 answers

sizeof(array)- This is the size of the pointer, which, as it turned out, is twice the size inton your platform.

It is not possible to get the length of an array in C. You just need to remember this yourself.

+11
source

First of all, it’s int **arrayThree = (int **)malloc(2 * sizeof(int))wrong, it must besizeof(int *)

Next, sizeof(array) / sizeof(int)matches sizeof(int *) / sizeof(int), which is not what you want.

, , "" , .

+4

, C, , .

, C, C . . : goo.gl/vYhkF.

+1

, arrayThree

int **arrayThree = malloc(2 * sizeof *arrayThree);

arrayThree int **, *arrayThree int *.

The reason why you sizeof (array) / sizeof (int)do not return what you expect is because it arrayis a type pointer int *, not an array type, so it sizeofreturns the number of bytes contained in the pointer object and not the number of marked elements.

It is impossible to find out only from the value of the pointer how many pointers point to; You must track this information separately.

0
source

All Articles