This may be a stupid question but how does the sizeof operator know the size of an array operand when you don\'t pass in the amount of elements in the array. I know it does
The sizeof operator 'knows' the size of all atomic datatypes, since structs, unions and arrays can only be constructed by assembling the atomic types it's easy to determine the size of array of any type. It uses basic arithmetic to determine complex types (during compile time).
Except in one case, sizeof
does it's thing at compile time. At compile time, the compiler keeps track of the full type of an object [Edit: well, everything it knows about the type of the object, anyway -- if the type isn't complete so that doesn't include the size, attempting to use sizeof
will fail], and sizeof
basically just "exports" one piece of that information from the compiler into the code being compiled, so it becomes essentially a constant in the resulting code.
The exception is when sizeof
is applied to variable length array (VLA)1. When applied to a VLA, sizeof
evaluates its operand (which it doesn't otherwise), and produces the actual size of the VLA. In this case, the result is not a constant.
1. VLAs officially became a part of C in C99, but some compilers supported them before that. Although not officially part of C++, some compilers (e.g., g++) include VLAs as an extension to C++ as well.
sizeof is calculated at compile-time. This is why when you create a dynamic array you create it the following way.
char * array;
int size;
//Get size somehow.
array = malloc(size*(sizeof(char)));
// now during the compile the compiler knows for sure the size of char. since it has to align them on the memory. At this point it the OS knows how much size it has to allocate.
Variable length arrays on the other hand are created on the Stack. But any malloc allocated memory would be created on the heap.
The compiler knows the size of each type in your application, and sizeof
just requests the compiler to produce that value for you.
Sizeof
is a compile time operator; it has as much information as the compiler does. (And obviously the compiler does know the size of the array).
This is why if you call sizeof
on a pointer you get the width of the pointer, not the size of the array to which that pointer points.
Quote from wiki:
It is the responsibility of the compiler's author to implement the sizeof operator in a way specific and correct for a given implementation of the language. The sizeof operator must take into account the implementation of the underlying memory allocation scheme to obtain the sizes of various datatypes. sizeof is usually a compile-time operator, which means that during compilation, sizeof and its operand get replaced by the result-value. This is evident in the assembly language code produced by a C or C++ compiler. For this reason, sizeof qualifies as an operator, even though its use sometimes looks like a function call.