Cpp的数组与指针关系
本文参考这里
- 一维数组:
#include <iostream>
using namespace std;
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *ptr = arr;
cout << "sizeof(int)=" << sizeof(int) << endl;
cout << "sizeof(ptr)=" << sizeof(ptr) << endl;
cout << "arr=" << arr << endl;
cout << "&arr[0]=" << &arr[0] << endl;
cout << "&arr=" << &arr << endl;
cout << "ptr=" << ptr << endl;
cout << "ptr+1=" << ptr + 1 << " : " << *(ptr + 1) << endl;
cout << "arr+1=" << arr + 1 << " : " << *(arr + 1) << endl;
cout << "&arr+1=" << &arr + 1 << endl;
return 0;
}
// 运行结果:
sizeof(int)=4
sizeof(ptr)=4
arr=0x28fed4
&arr[0]=0x28fed4
&arr=0x28fed4
ptr=0x28fed4
ptr+1=0x28fed8 : 2
arr+1=0x28fed8 : 2
&arr+1=0x28fefc
- 二维数组
#include <iostream>
using namespace std;
int main()
{
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int (*ptr)[4] = arr;
cout << "sizeof(int)=" << sizeof(int) << endl;
cout << "sizeof(ptr)=" << sizeof(ptr) << endl;
cout << "arr=" << arr << endl;
cout << "&arr[0]=" << &arr[0] << endl;
cout << "&arr=" << &arr << endl;
cout << "ptr=" << ptr << " : " << **ptr << endl;
cout << "ptr+1=" << ptr + 1 << " : " << **(ptr + 1) << endl;
cout << "arr+1=" << arr + 1 << " : " << **(arr + 1) << endl;
cout << "&arr+1=" << &arr + 1 << endl;
return 0;
}
//运行结果
sizeof(int)=4
sizeof(ptr)=4
arr=0x28fecc
&arr[0]=0x28fecc
&arr=0x28fecc
ptr=0x28fecc : 1
ptr+1=0x28fedc : 5
arr+1=0x28fedc : 5
&arr+1=0x28fefc