数组指针(二维数组的指针)

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 
 6 int main()
 7 {
 8     int v[2][2]={{1,2},{3,4}};
 9     cout<<"v = "<<v<<endl;
10     cout<<"*v = "<<*v<<" &v = "<<&v<<endl;
11     cout<<"*v+1 = "<<*v+1<<endl;
12     cout<<"*(v+1) = "<<*(v+1)<<" &v[1] = "<<  &v[1]<<endl;
13     cout<<"v[0] = "<<v[0]<<" &v[0] = "<<  &v[0]<<endl;
14     cout<<endl;
15 
16     cout<<"**v = "<<**v<<endl;
17     cout<<"**(v+1) = "<<**(v+1)<<endl;
18     cout<<"*(*v+1) = "<<*(*v+1)<<endl;
19     cout<<"*(v[0]+1) = "<<*(v[0]+1)<<endl;
20     cout<<"*(v[1]) = "<<*(v[1])<<endl;
21 
22     return 0;
23 }

运行结果为:

v = 0012FF50
*v = 0012FF50 &v = 0012FF50
*v+1 = 0012FF54
*(v+1) = 0012FF58 &v[1] = 0012FF58
v[0] = 0012FF50 &v[0] = 0012FF50

**v = 1
**(v+1) = 3
*(*v+1) = 2
*(v[0]+1) = 2
*(v[1]) = 3

由此看出,v表示数组首地址,*v表示第一行数组的首地址,那么*v+1则表示在数组第一行一个元素基础上移动sizeof(int)。而v+1表示移动一个数组大小,移动到第二行的首个元素。即,对于一个二维数组来说,v,v+1都是对于二维数组而言的,在其上的移动操作是以行为单位。若想得到元素的值,必须解引用两次。解引用一次,把它们转换为一个一维数组。

同样的,v[0],v[1]表示第一行,第二行首元素地址。v[0],v[1]可以看做一个一维数组,他们是相应行的首地址。

这里顺便提一下,对于一维数组来说,数组名本身就是指针,在加一个&,就变成了双指针,这里的双指针就是二维数组,加1,就是数组整体加一行,即最后一个元素的下一个元素(虽然并不存在)。

例如:

1 int a[]={1,2,3};
2 int *ptr=(int*)(&a+1);
3 cout<<*(ptr-1)<<endl;

输出结果为:3.

原文地址:https://www.cnblogs.com/yitianke/p/3055459.html