I am reading a great book by Stephen Prata. Unfortunately I don't understand something. It is about array and pointers. So there is array tab. He wrote, that tab is the address for first element of array -> that is ok, but &tab is address for whole array <- I don't understand this. What does it means? &tab shows all address of array (of course not), middle address of all elements of array, the last one?
In C and C++ there are two aspects to a pointer:
tab
and &tab
indicate the same address, but they have different type. They denote different objects: &tab
is a large array, and tab
(aka. &tab[0]
) is a sub-object of that array.
It's no different to this situation:
struct S
{
int x;
int y;
};
S s;
S *p1 = &s;
int *p2 = &s.x;
In this case p1
and p2
both point to the same address, but they have different types, and point to different objects which occupy the same space.
tab is the address for first element of array
this is correct, for char arr[1];
you can write char* p = arr;
, here we say that arr decays to pointer to its first element.
&tab is address for whole array
it means its type is a pointer to array, ie. char(*)[1]
. Their pointer values (arr and &arr) are equal but the types differ. So below will compile:
char (*pp)[1] = &arr; // pointer to array
char (&rp)[1] = arr; // reference to array
but this will not compile:
char* pp = &arr; // error, types differ
You can use below trick to find what type given expression/variable really is. Compiler will show you an error from which you can read actual types:
template <typename T>
struct TD;
int main()
{
char arr[1];
//char* pp = &arr; // error, types differ
TD<decltype(arr)> dd; // is char[1], no decay to char* here
TD<decltype(&arr[0])> dd; // is char*
//TD<arr> dd; // char(*)[1]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.