Home > Software design >  C: Sizeof of 2D-array - difference between pointer and first element
C: Sizeof of 2D-array - difference between pointer and first element

Time:03-26

I have an array similar to the following 2D array in C:

uint16_t myArray[2][14] = {
                    { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
                    { 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114} 
                };

I wanted to get the size of the array and used:

printf("size: %d \n", sizeof(myArray) / sizeof( * myArray));

with the result

size: 2

When I used the first element of the first subarray

printf("size: %d \n", sizeof(myArray) / sizeof(myArray[0][0]));

... I got the correct result:

size: 28

Is this because I initialized my array with 2 subarrays or is there another explanation?

CodePudding user response:

When you get the length of the array using this:

printf("size: %d \n", sizeof(myArray) / sizeof( * myArray));

You are getting the size of the array and then dividing it by the size of the first element, which is in turn another array. Because there is another array inside it with a length described in the variable declaration, it will get the size of the array rather than a *uint16_t. In effect, you are getting the amount of memory allocated by the whole array, and then dividing it by the size of the amount of memory allocated by the array inside, which as there are only two elements is 2.

Whole 2D array (28 * sizeof(uint16_t)): 001, 002, 003, 004, 005, 006, 007, 008, 009, 010, 011, 012, 013, 014, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114

1D array inside 2D (14 * sizeof(uint16_t)): 001, 002, 003, 004, 005, 006, 007, 008, 009, 010, 011, 012, 013, 014

When using the size of the element inside, you are dividing 28 * sizeof(uint16_t) by 14 * sizeof(uint16_t), which is 2. However, when using the size of the element inside, you are dividing 28 * sizeof(uint16_t) by sizeof(uint16_t), which is 28.

Hope this makes sense :)

  • Related