简体   繁体   English

C ++内存和指针地址

[英]C++ addres to memory and pointers

I am reading a great book by Stephen Prata. 我正在读斯蒂芬·普拉塔(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. 他写道,选项卡是数组->的第一个元素的地址,可以,但是&tab是整个数组的地址<-我不明白。 What does it means? 这是什么意思? &tab shows all address of array (of course not), middle address of all elements of array, the last one? &tab显示数组的所有地址(当然不是),数组所有元素的中间地址,最后一个?

In C and C++ there are two aspects to a pointer: 在C和C ++中,指针有两个方面:

  • The memory address it points to 它指向的内存地址
  • The type of what it is pointing to 它指向的类型

tab and &tab indicate the same address, but they have different type. tab&tab表示相同的地址,但类型不同。 They denote different objects: &tab is a large array, and tab (aka. &tab[0] ) is a sub-object of that array. 它们表示不同的对象: &tab是一个大数组,而tab (又名&tab[0] )是该数组的子对象。

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. 在这种情况下, p1p2都指向相同的地址,但是它们具有不同的类型,并指向占用相同空间的不同对象。

tab is the address for first element of array tab是数组第一个元素的地址

this is correct, for char arr[1]; 对于char arr[1]; ,这是正确的char arr[1]; you can write char* p = arr; 你可以写char* p = arr; , here we say that arr decays to pointer to its first element. ,这里我们说arr衰减到指向其第一个元素的指针。

&tab is address for whole array &tab是整个数组的地址

it means its type is a pointer to array, ie. 这意味着它的类型是指向数组的指针,即。 char(*)[1] . char(*)[1] Their pointer values (arr and &arr) are equal but the types differ. 它们的指针值(arr和&arr)相等,但类型不同。 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]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM