二维数组中的指针算术

Pointer arithmetic in 2D array

本文关键字:指针 二维数组      更新时间:2023-10-16

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

我已经为数组编写了以下程序。我知道返回数组的基址,并且数组的名称指向该基址。所以,在一维数组的情况下,我可以理解

到达 + 1

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

arr + 4字节

但是,在 2D 阵列的情况下,它略有不同。我从下面的cout语句中了解到,在内存中arr2D[0],arr2D[1]。arr2D[4] 将依次分配 20 字节,因为有 5 个列,即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;
}

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

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

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

来自 cpp首选项:

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

所以 arr2D 衰减成一个指向大小为 5 的 int 数组的指针,其大小为 20。