[英]C++ Memory Address Allocation
Apologies i got frustrated and posted question through mobile without proper details 道歉,我感到沮丧,并在没有适当详细信息的情况下通过手机发布了问题
Consider the following C++ code: 考虑以下C ++代码:
int arr[2];
arr[0] = 10;
arr[1] = 20;
// cout << &arr;
for (int i = 0; i < 2; i++)
{
cout << &arr + i << "\t\t"<<endl;
}
cout << sizeof (arr);
cout in for loop prints following cout进入for循环打印
0x7ffeefbff580 0x7ffeefbff588 0x7ffeefbff580 0x7ffeefbff588
which is 8 bytes farther than the first element 比第一个元素多8个字节
My question is why it is 8 bytes further and not 4 bytes if on my machine sizeof(int) is 4? 我的问题是,如果在我的机器上sizeof(int)是4,为什么还要再增加8个字节而不是4个字节?
Now that you gave us the code we can answer your question. 现在,您已经给我们提供了代码,我们可以回答您的问题。
So the confusing piece is this: &arr + i
. 因此,令人困惑的是: &arr + i
。 This does not do what you think it does. 这并没有按照您的想法做。 Remember that &
takes precedence over +
. 请记住, &
优先于+
。 And so you take address of arr
and move it forward i
times. 因此,您取了arr
地址并将其向前移动i
次。
Pointer arithmetic works in such a way that &x + 1
moves the pointer forward by size(x)
. 指针算术的工作方式是&x + 1
将指针向前移动size(x)
。 So in your case what is size(arr)
? 那么在您的情况下, size(arr)
多少? It is 8 because it is 2-element array of integers (I'm assuming ints are of size 4). 它是8,因为它是2的整数数组(我假设int的大小为4)。 And so &arr + 1
actually moves the pointer 8 bytes forward. 因此, &arr + 1
实际上会将指针向前移动8个字节。 The exact thing you experience. 您体验的确切内容。 You don't ask for next int, you ask for next array . 您不要求下一个int,而是要求下一个array 。 I encourage you to play around, for example define arr
as int[3]
(which is of size 12) and see how the pointer moves 12 bytes forward. 我鼓励您尝试一下,例如将arr
定义为int[3]
(大小为12),然后看看指针如何向前移动12个字节。
So first solution is to do arr + i
without &
. 因此,第一个解决方案是不使用&
进行arr + i
。 We can apply pointer arithmetic to an array in which case it decays to a pointer type int*
. 我们可以将指针算术应用于数组,在这种情况下,它会退化为指针类型int*
。 Now since int
is of size 4 then arr + 1
points correctly to a memory segment 4 bytes forward. 现在,由于int
的大小为4,则arr + 1
正确指向向前4个字节的内存段。
But what I suggest is to stay away from pointer arithmetic and do &arr[i]
instead. 但是我建议不要使用指针算法,而要使用&arr[i]
。 This does the same thing but IMO is less error prone, less confusing and tells us more about the intent. 这样做是一样的,但是IMO不太容易出错,也不会造成混乱,并且可以告诉我们更多有关此意图的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.