为什么在访问ptr [i] [j]时,int ** ptr指向与int arr [3] [3]相同的地址? [英] Why doesn't int** ptr point to the same address as int arr[3][3] when accessing ptr[i][j]?
本文介绍了为什么在访问ptr [i] [j]时,int ** ptr指向与int arr [3] [3]相同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我回答这个问题,但是当我测试以下代码
我很困惑。
I was answering this question but when I tested the following code I got confused.
#include <iostream>
using namespace std;
int main()
{
int **ptr;
int arr[3][3];
ptr =(int **) arr;
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
cout << &arr[i][j] << " =? ";
cout << &(ptr[i][j]) << endl;
}
}
return 0;
}
但我得到这个输出:
0x7fff5700279c =? 0
0x7fff570027a0 =? 0x4
0x7fff570027a4 =? 0x8
0x7fff570027a8 =? 0
0x7fff570027ac =? 0x4
0x7fff570027b0 =? 0x8
0x7fff570027b4 =? 0
0x7fff570027b8 =? 0x4
0x7fff570027bc =? 0x8
推荐答案
int ** ptr
和 int arr [3] [3]
不同,因为:
-----------------------------------
| C | Maths |
-----------------------------------
| ptr + 1 | ptr + sizeof(int*) |
-----------------------------------
| arr + 1 | arr + 3 * sizeof(int*) |
-----------------------------------
所以你不会得到相同的结果(此外, ptr
和 arr
可能不具有相同的内存表示)。
So you won't get the same results at all (moreover, ptr
and arr
may not have the same memory representation).
int (*ptr)[3] = arr;
将工作,因为只有 arr
衰减到指针。
will work, since only the first dimension of arr
decays to a pointer.
这篇关于为什么在访问ptr [i] [j]时,int ** ptr指向与int arr [3] [3]相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文