我正在学习二维数组指针,这是我的代码。我不知道为什么这一行:
cout<<"Address of 1st part = "<<*ptr`
当此行显示地址时,未显示地址:
cout<<"Address of 1st part = "<<*(A)`
这两行意味着同样可以帮助我。
#include <iostream>
using namespace std;
int main()
{
int A[2][3]={{1,2,4},{5,8,3}};
int *ptr;
ptr=&A[0][0];
cout<<"Address 1st part = "<<A<<endl;
cout<<"Address 2nd part = "<<A+1<<endl;
cout<<"Address 1st part = "<<ptr<<endl;
cout<<"Address 2nd part = "<<ptr+1<<endl;
cout<<"Address of 1st part = "<<*(A)<<endl;
cout<<"Address of 1st part = "<<*ptr<<endl;
cout<<"Address"<<*(A+1)+1<<endl;
cout<<*(A+1)+2<<endl;
return 0;
}
输出
Address 1st part = 0x7fffb6c5f660
Address 2nd part = 0x7fffb6c5f66c
Address 1st part = 0x7fffb6c5f660
Address 2nd part = 0x7fffb6c5f664
Address of 1st part = 0x7fffb6c5f660
Address of 1st part = 1
Address0x7fffb6c5f670
0x7fffb6c5f674
答案 0 :(得分:1)
这两行实际上并不相同。多维数组不等同于指向其基本类型的指针。
A
的类型为int [2][3]
,相当于int *[3]
。 *A
的类型为int[3]
,而非int
。连续的指向元素之间的步骤sizeof *A
等于sizeof(int)*3
。
ptr
的类型为int *
。 *ptr
的类型为int
。此处的步骤sizeof *ptr
等于sizeof(int)
。