Question

So C/C++ arrays don't know about their length, right? But then how can the function sizeof(array) work and give us the proper size in bytes when it shouldn't be able to know the number of elements in the array?

Was it helpful?

Solution

So C/C++ arrays don't know about their length, right.

Your assumption is wrong. With the exception of variable length arrays introduced in C99, arrays in both C and C++ have a size that is known in compile time. The compiler knows their size.

Your confusion is probably because there are times when array names decay into a pointer to its first element (like when passed as function argument), it's true that the size information is lost here.

But when sizeof is used on an array, the array is not converted to a pointer. This is your other confusion: sizeof is not a function, it's an operator.

OTHER TIPS

I will quote the relevant portions of C99 standard. §6.5.3.4 ¶2 says

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

It also says in the same section §6.5.3.4 ¶1

The sizeof operator shall not be applied to an expression that has function type or an incomplete type.

About the array type, §6.2.5 ¶20 says

An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. Array types are characterized by their element type and by the number of elements in the array.

It again says in §6.2.5 ¶22

An array type of unknown size is an incomplete type.


So to summarize the above, the size of an array is known to the compiler (determined using sizeof operator) when you also specify the size of the array, i.e, when it's a complete type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top