【发布时间】:2016-03-12 08:16:09
【问题描述】:
我有一些关于 C++ 中地址的有趣问题。 我有这样的代码:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int N = 50 + rand() % 151;
int arr[N];
int arr2[N];
int *ptr1;
ptr1 = &arr[0];
for(int i = 0; i < N; i++){
cout << "Address1: "<< &arr[i]<< "\t" << "Address2: " << &arr2[i] << endl;
}
}
此代码有效,但地址分配让我感到害怕。这样的输出合法吗?我认为这有点奇怪,第二个数组在内存中的位置比第一个数组早。 如果有人知道出了什么问题,请解释一下出了什么问题,因为根据定义顺序,首先必须是第一个数组的地址,而不是第二个数组的地址。 那是在 Ubuntu 中用 g++ 编译的。
Address1: 0xbf9ab1b8 Address2: 0xbf9ab028
Address1: 0xbf9ab1bc Address2: 0xbf9ab02c
Address1: 0xbf9ab1c0 Address2: 0xbf9ab030
Address1: 0xbf9ab1c4 Address2: 0xbf9ab034
Address1: 0xbf9ab1c8 Address2: 0xbf9ab038
Address1: 0xbf9ab1cc Address2: 0xbf9ab03c
Address1: 0xbf9ab1d0 Address2: 0xbf9ab040
Address1: 0xbf9ab1d4 Address2: 0xbf9ab044
Address1: 0xbf9ab1d8 Address2: 0xbf9ab048
Address1: 0xbf9ab1dc Address2: 0xbf9ab04c
Address1: 0xbf9ab1e0 Address2: 0xbf9ab050
Address1: 0xbf9ab1e4 Address2: 0xbf9ab054
...
【问题讨论】:
-
投反对票,因为这里根本没有进行任何研究。
-
实际上值遵循定义顺序,因为堆栈向下增长。但在任何情况下,数据放入堆栈的顺序都不是标准规定的。
-
@Jack,我听说有些架构是堆栈向上增长的。
-
@RSahu:除非另有说明,否则我假设使用任何标准 C++ 编译器的标准 x86 架构
-
没有人学习初始化了吗?
int *ptr; ptr = &arr[0];应该是一条语句:int *ptr = &arr[0];。
标签: c++ arrays linux memory g++