Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the address of the array equal to that of its first element in C++?

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?

like image 983
xskxzr Avatar asked Jan 07 '23 04:01

xskxzr


2 Answers

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.

like image 156
molbdnilo Avatar answered Jan 09 '23 19:01

molbdnilo


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.

like image 25
songyuanyao Avatar answered Jan 09 '23 19:01

songyuanyao