简体   繁体   English

为什么在c ++中使用静态数组&a和相同?

[英]Why is &a and a same in case of static arrays in c++?

int a[10];

Now here &a and a is same, I don't clearly understand logic why is it so. 现在这里和a和a是一样的,我不清楚逻辑为什么会如此。 Can I say that value of a is same as &a and *(a) is a[0]. 我可以说a的值与&a相同而*(a)是a [0]。 (But how a is not a pointer). (但是a不是指针)。 In case of dynamic array things are clear to me. 在动态数组的情况下,我很清楚。

int *da = new int[10];

value of da is base address, &da gives the address where pointer is stored, and we deference da to reach da[0]. da的值是基地址,&da给出指针存储的地址,我们deference da到达da [0]。

They are not the same. 她们不一样。

a is an int[10] type; aint[10]类型; an array . 一个数组

&a is a pointer to an int[10] type. &a是指向int[10]类型的指针。

In certain situations (passing to functions, when used in arithmetic expressions), a decays to an int* type. 在某些情况下(传递给函数,在算术表达式中使用时), a 衰变到一个int*类型。 You can then use pointer arithmetic to reach other elements of the array. 然后,您可以使用指针算法来到达数组的其他元素。 That could be what is causing your confusion. 这可能是造成你困惑的原因。

da is an int* type. da是一个int*类型。

The only thing that decays to itself is a function pointer . 衰弱的唯一因素函数指针

well 'a' and '&a' are definitely not the same 'a'和'&a'绝对不一样

int a[10] takes up a specific block from memory to allocate exactly 10 integers and this block is called a. int [10]从内存中占用一个特定的块来精确分配10个整数,这个块称为a。

'&a' refers to the memory address of this memory block of 10 integers you made. '&a'指的是你所做的10个整数的内存块的内存地址。 it's like you have a hotel room (the array of 10 elements) in your hotel. 就像你在酒店里有一个酒店房间(10个元素的阵列)。 And (your memory address) '&a' refers to your room number, your address. 并且(您的记忆地址)'&a'是指您的房间号码,您的地址。

now saying for example int *p = &a means I'm making an integer pointer 'p' that can only point to integers, and i'm giving it the memory address of 'a' (the array of integers) so it can point to it. 现在说例如int * p =&a意味着我正在制作一个只能指向整数的整数指针'p',并且我给它的内存地址为'a'(整数数组)所以它可以指向它。

so : 所以:

int a[10] is your hotel room; int a [10]是你的酒店房间;

&a is your room number; &a是您的房间号码;

*p = &a is the key chain attached to your room number (ur keychain points to ur room number, your address); * p =&a是您房间号码附带的钥匙链(您的钥匙串指向您的房间号码,您的地址);

this is why sometimes we use : int *da = new int[10]; 这就是为什么我们有时会使用:int * da = new int [10]; to immediately allocate in memory a space for 10 integers and directly point a pointer (in this case da) to it. 立即在内存中为10个整数分配空间,并直接指向它的指针(在本例中为da)。

Hope this helps. 希望这可以帮助。

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

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