C++,数组中的地址

C++, addresses in array

我有一些关于 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
...

I think that it is kind of wierd, that second array, locates earlier in memory than 1st array.

不是。完全正常。

according to defenition order, first must be adresses of 1st array, than adresses of second.

不知道你从哪里听说块作用域中的对象地址是按照定义顺序递增的。通常,由于 stacks 工作方式的性质,事实恰恰相反。

无论哪种方式对您来说都不重要;您的计算机可以将对象放置在任意位置。

获取有关计算机体系结构的书籍以获取更多信息。