Information regarding the size of an array is pushed onto the program's stack followed by the array itself. This assumption is confirmed with the following code:
1 2
|
int Array[5];
std::cout << sizeof( Array );
| |
The above code will output 5. If the compiler did not keep track of the array's size, "
sizeof" would yield some undefined value or even an error.
Though, in some circumstances, "
sizeof" does yield a value, but a value that's unexpected. For instance:
1 2 3 4
|
void Function( int Array[] )
{
std::cout << sizeof( Array );
}
| |
One could assume that the "
Array" parameter is an array, but they'd be wrong because "
Array" is a pointer, and in C++, pointers always consume the same amount of memory. Common outputs for "
sizeof" in the above code would be either 4- or 8-bytes.
If the compiler knows the length of the array, why can't I retrieve the size of the array with "sizeof" in the above code?
Because "
Array" is a pointer, the compiler cannot assume that the address pointed-to by the pointer is an element of an array. Just because the declaration of "
Array" looks like a declaration of an array, you can't assume that "
Array" refers to an array. Remember: a pointer can point to any piece of storage so long as the storage has the same type as the pointer's type-identifier. For example:
Here, "
Pointer" can point to any "
int" storage, regardless of whether the storage is associated with an array, class or name-space.
Wazzak