我正在学习C++。所以,请问这个长问题。

我已经为数组编写了以下程序。我了解返回了数组的基地址,并且数组的名称指向该数组。因此,对于一维阵列,我可以理解



返回数组下一项的地址,即



但是,对于2D阵列,情况有所不同。我从下面的 cout 语句中了解到,在内存arr2D [0],arr2D [1] .. arr2D [4]中,由于存在5个列,因此将一个接一个地分配20个字节,即 5 * 4字节

arr2D和arr2D [0]指向与预期相同的基地址; 第43和45行

所以,如果我这样做



我得到了arr2D [1]的地址; 第47行。但是,当我这样做



我从基址得到了一个100字节的内存地址; 第50行。我不明白为什么。有人可以向我解释吗?

#include <iostream>

using namespace std;

int main() {

int arr[5] = {0,1,2,3,4};

cout << "Printing arr" << endl;
for (int i = 0; i < 5; i++) {
    cout << *(arr + i) << " ";
}
cout << endl;

cout << "Base address of 'arr': " << (unsigned long) arr
     << " EQUALS " << "&arr: " << (unsigned long) &arr
     << endl;

cout << "Address of 2nd item i.e. i = 1 is: " << (unsigned long) (arr+1)
     << endl;

cout << "arr[1] = " << arr[1] << ", "
     << "1[arr] = " << 1[arr] << ", "
     << "*(arr + 1) = " << *(arr + 1)
     << endl << endl;


int arr2D[5][5] = {{1,2,3,4,5},
                   {3,4,5,6,7},
                   {5,6,7,8,9},
                   {7,8,9,10,11},
                   {9,10,11,12,13}};

cout << "Printing arr2D" << endl;
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        cout << *(arr2D[i] + j) << " ";
    }
    cout << endl;
}
cout << endl;


cout << "Base address of arr2D = " << (unsigned long) arr2D << endl; // this is fine

cout << "Address of arr2D[0] = " << (unsigned long) &arr2D[0] << endl; // this is fine

cout << "Address of arr2D[1] = " << (unsigned long) arr2D[1] << " EQUALS "
     << (unsigned long)(arr2D[0] + 5) << endl; // this is fine

cout << "Address of arr2D[1] = " << (unsigned long) arr2D[1] << " NOT EQUALS "
     << (unsigned long)(arr2D + 5) << endl; // I do not understand this, as arr2D and arr2D[0] is same

cout << "Address of arr2D[1][0] = " << (unsigned long)&arr2D[1][0] << endl;

cout << "arr2D[1][0] = " << *((arr2D[0] + 5) + 0) << endl;
}

最佳答案

arr2D[0]arr2D指向相同的地址,但它们指向不同的类型。
arr2D[0]是2D数组的第一行,因此它衰减为指向该行第一元素(单个int)的指针。同时,arr2D是2D数组(数组的数组),因此它衰减到指向第一行的指针(5个元素的数组)。

如您所知,指针算术被缩放为指针所指向的对象的大小。由于arr2D指向5个元素int数组,因此所指向的每个对象的大小为4 * 5 = 20字节(假定为32位int),因此将指针增加5会导致20 * 5 = 100字节的差。

10-07 13:21
查看更多