二維數組和二維指針


原文地址:http://www.cppblog.com/glxhyt/archive/2011/11/21/160668.html

入職一年了,這一年自己學到許多,但是忘記也很多,於是決定定下心來整理以前學到的,並且繼續學習

    
    二維數組和二級指針,這真是頭疼的問題,困擾了我好幾次,
   
    先轉一下 wanpengcoder 的二維數組和二級指針 

前兩天寫個程序,傳參數的時候想傳個二維數組進去,結果悲劇了,函數寫成Fun (int **p){},原來沒有這么寫過,

以為這么寫也是對的,結果錯了,查了些資料,做個總結。

Fun (int **p){}這里面的int **p //這里的p不是二維數組的指針,而是指向指針的指針,即二級指針。

正確的二維數組的指針應該是:Int a[2][2];Int (*p)[2];//定義時無論數組維數,只可忽略第一維

例如:int a[2][2]={0,1,2,3};

int **p=(int**)a;//強制將二維數組指針轉為指向指針的指針

則此時p[0]=0;p[1]=1;p[2]=2;p[3]=3;

而p[0][0]=*(*(p+0)+0)=**p;

p[0][1]=*(*(p+0)+1);

對於p[0][0]:由於*p=0; ====> **p=*(0);引用地址為零的內存,必然是錯誤的。

對於p[0][1]=*(*p+1)====>*(4),引用了非法內存同樣,

對於p[1][0]=*(1),p[1][1]=*(5),均引用了非法內存所以說,二位數組並不能簡單的轉換成指向指針的指針。

二維數組其實只是一個指針,而二級指針是指向指針的指針,所以二者並不等價。如上例所示:int a[2][2];

a是指向整個數組的首地址,並不是int **;所以不要指望向函數fun里面傳實參 p=a;

 

感謝sld666666,我覺得那個應該是和下面的情況類似把,中間有個強制轉換的過程:

 

#include <iostream>

 

void fun(char ** p)

{

char (*p1)[10] = (char(*)[10])p;

std::cout<<p1[0][0]<<std::endl;

}

 

int main(int argc, char* argv[])

{

char data[][10] = {"abc","def"};

fun((char **)data);

return 0;

}

----------------------------------------------------------------華麗的分割線---------------------------------------------------------------------------------------------------------------------------

 

<c程序設計語言>中的關於這個的解釋:

Newcomers to C are sometimes confused about the difference between a two-dimensional array and an array of pointers, such as name in the example above. Given the definitions

int a[10][20];

int *b[10];

then a[3][4] and b[3][4] are both syntactically legal references to a single int. But a is a true two-dimensional array: 200 int-sized locations have been set aside, and the conventional rectangular subscript calculation 20 * row +col is used to find the element a[row,col]. For b, however, the definition only allocates 10 pointers and does not initialize them; initialization must be done explicitly, either statically or with code. Assuming that each element of b does point to a twenty-element array, then there will be 200 ints set aside, plus ten cells for the pointers. The important advantage of the pointer array is that the rows of the array may be of different lengths. That is, each element of b need not point to a twenty-element vector; some may point to two elements, some to fifty, and some to none at all.

Although we have phrased this discussion in terms of integers, by far the most frequent use of arrays of pointers is to store character strings of diverse lengths, as in the function month_name. Compare the declaration and picture for an array of pointers:

char *name[] = { "Illegal month", "Jan", "Feb", "Mar" };


with those for a two-dimensional array:

char aname[][15] = { "Illegal month", "Jan", "Feb", "Mar" };




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: