This can be guaranteed in C because of the following sentence in WG14/N1570:
6.2.5/20 ... An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type.
But in WG21/N4527, i.e. in C++, the corresponding sentence becomes
8.3.4/1 ...An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.
while the word "describes" is changed to "contains", which cannot guarantee that the address of the array equals to that of its first element. Is this change intentional or unintentional? If it is intentional, does the address of the array equal to that of its first element in C++? If it does, which paragraph in the C++ standard can guarantee this?
I don't think it's stated explicitly anywhere, but I believe it follows from 5.3.3 Sizeof
:
the size of an array of n elements is n times the size of an element
that the only thing that can be stored at the array's starting address is the array's first element.
In C++ it is guaranteed by 4.2/1 Array-to-pointer conversion [conv.array], (bold by me)
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.
That means if you want to take the address of an array in C++, you would get a pointer which points to the first element of the array. i.e.
int a[10];
int* p1 = a; // take the address of array
int* p2 = &a[0]; // take the address of the first element of the array
The standard guarantees that p1
and p2
will point to same address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With