'How is the size of a C array known by the compiler? [duplicate]

Say I have some array ar, I know sizeof(ar); will return the total length of the array in bytes (size of data value type * the total number of array spaces).

If the array name ar is converted to a base pointer address and subscripts are converted to an integer offset by the C compiler, where is the size of the array stored in memory?

Or is it similar to a string where there is some special value that denotes the termination of the array?

Maybe I'm misunderstanding how arrays work in C but I can't work out how the sizeof() function would obtain the size of an array.

Any information would be much appreciated, thanks!

c


Solution 1:[1]

The size isn't stored anywhere. The compiler knows what the size of an array is (assuming the actual array is in scope) and can calculate it at compile time when sizeof array is used.

When an array is passed to a function and therefore converted to a pointer to its first element, the size is no longer available so the size must also be passed to the function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dbush