What does this mean?

In my book it says

An array records no information about its size, so you cannot use the range-based for loop with an array passed as an argument to a function.

I dont quite understand but, is it because arrays names are converted to pointers and the address is stored into the parameter?

And if arrays dont store their size how does a range based loop even work.

Can someone please help?
I think: when you pass an array as a function, the prototype can seem like that: "type function_name (type array[])", which is like "type function_name (type array*)" so, it is a pointer. The function doesn't know how big is the array, so it's the developer who have to know it... You were right, if I understood the question
Oh ok thank you.

So the book didnt quite explain it exactly right?
And if arrays dont store their size how does a range based loop even work.

You said
An array records no information about its size, so you cannot use the range-based for loop with an array passed as an argument to a function.
closed account (zb0S216C)
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:

 
int *Pointer;

Here, "Pointer" can point to any "int" storage, regardless of whether the storage is associated with an array, class or name-space.

Wazzak
Last edited on
@Framework

Thank you you cleared it up.
Topic archived. No new replies allowed.