Quote:Original post by swiftcoder
If I declare 'char A[5]', A is a pointer. Albeit to a either the static data section or to a region on the stack, and immutable.
No.The
address of an array variable is the address of its contents. This is unlike pointers, the
address of which is irrelevant, but the
value of which contains the address of something else.
The sequence of operations performed for accessing A[3] is:
- Get the address of A, add 3, dereference (if A is an array).
- Get the address of A, dereference, add 3, dereference (if A is a pointer).
That is, accessing a memory buffer through a pointer requires an additional dereference in order to access the value of the pointer, which is the address of the buffer.
Quote:But in fact that is just a syntactical issue, and you *have* created an unnecessary temporary pointer. And are you quite sure about that? I am not near a compiler to test that, but it seems to me you should get the same result whether you pass an array, or a reference to an array (note that I never mentioned using a pointer directly).
When you pass a reference to an array, the type is conserved. Since the array size is encoded in the type, it is accessible to the compiler. On the other hand, you cannot pass an array by value in C and C++. The array automatically decays to a pointer if you do, and the size information is lost. The only way to conserve type information is using a reference:
#include <iostream>int byref(int (&a)[5]){ return sizeof(a);}int byval(int a[5]){ return sizeof(a);}int main(){ int a[5]; std::cout << byref(a) << std::endl << byval(a) << std::endl;}
Outputs:
204