2D数组中的指针算术

时间:2019-06-01 04:38:54

标签: c++ arrays

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

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

  

arr + 1

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

  

arr + 4bytes

但是,对于2D数组,则有些不同。我从下面的 cout 语句中了解到,在内存arr2D [0],arr2D [1] .. arr2D [4]中,所有内存将依次分配20个字节,因为共有5个cols,即 5 * 4字节

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

所以,如果我这样做

  

arr2D [0] + 5

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

  

arr2D + 5

我从基地址得到一个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;
}

2 个答案:

答案 0 :(得分:2)

来自cppreference

  

当应用数组到指针的衰减时,多维数组是   转换为指向其第一个元素的指针(例如,指向其第一个元素的指针   第一行或其第一平面):应用数组到指针的衰减   只有一次

因此arr2D衰减为一个指向大小为5的int数组的指针,该数组的大小为20。

答案 1 :(得分:2)

arr2D[0]arr2D指向相同的地址,但它们指向不同的类型

arr2D[0]是2D数组的第一行,因此它衰减到指向该行第一元素(单个int)的指针。同时,arr2D是2D数组(数组的数组),因此它衰减到指向第一行的指针(5个元素的数组)。

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