D
D
dandropov952018-08-23 13:18:15
C++ / C#
dandropov95, 2018-08-23 13:18:15

How does sizeof calculate the size of an array?

int arr[SIZE] = { 1, 2, 3, 4, 5 };

printf("%zd\n", sizeof(*(arr + 0))); // 4
printf("%zd", sizeof(arr)); // 20

How sizeof calculates the size of an array, if passing the array name to the function, in fact, a pointer to the first element is passed, in this case sizeof receives a pointer to int (sizeof (int) == 4). How does the function find out the number of elements? According to the idea, when passing sizeof a pointer, the size of this pointer should be returned (in my case 8).
sizeof(&arr[0]) == 8.
How it all works if // &arr[0] == arr
Output the same address:
printf("%p\n", &arr[0]);
printf("%p\n", arr);

But if you call sizeof with these values, then there will be different results.
printf("%zd\n", sizeof(&arr[0])); // Выводится размер указателя
printf("%zd\n", sizeof(arr)); // Выводится размер всего массива, хотя и то и то являются адресами первого элемента

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-08-23
@res2001

sizeof is not a function (even though it looks like it) - it's a size operation.
sizeof is always evaluated at compile time, i.e. in the executable file, instead of calling sizeof, there will already be a calculated constant.
When the compiler knows the size of the array, like in your example, it will return the full size of the array.
But if you pass an arbitrary pointer to sizeof (namely, a pointer, not a static array), it will return the size of the pointer.
A static array is not a pointer. Pointer - at the execution stage, it occupies a place in memory to store the address. A static array takes up space in memory to store the array data.
So a static array is not a pointer. Although often the compiler treats a static array name as a pointer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question