在作這道題時:ios
32位環境下,int *p=new int[10];請問sizeof(p)的值爲()
A、4 B、10 C、40 D、8數組
我覺得正確答案爲C,int類型爲32位,佔四個字節,10個天然就是40了,結果正確答案爲A,只是指針p佔的空間。函數
所以寫段代碼測試一下:測試
1 #include<iostream> 2 using namespace std; 3 void fun(int P[])//P這裏做爲指針使用 4 { 5 cout<<"在函數中"<<sizeof(P)<<endl; 6 } 7 int main() 8 { 9 int A[10]; 10 int* B=new int[10]; 11 cout<<"數組名"<<sizeof(A)<<endl; 12 cout<<"指針"<<sizeof(B)<<endl; 13 fun(A); 14 }
或者spa
1 #include<iostream> 2 using namespace std; 3 void fun(int *P) 4 { 5 cout<<"在函數中"<<sizeof(P)<<endl; 6 } 7 int main() 8 { 9 int A[10]; 10 int* B=new int[10]; 11 cout<<"數組名"<<sizeof(A)<<endl; 12 cout<<"指針"<<sizeof(B)<<endl; 13 fun(A); 14 }
結果輸出: .net
數組名40
指針4
在函數中4指針
因而可知,數組名並非徹底等同於指針。雖然它們均可以經過指針方式訪問數組。code
可是數組在做爲函數參數傳遞過程當中,會退化成指針。這也是爲何指針做爲參數傳遞時,常常要一個長度。(wsj注:指針做爲形參時,一般再加上一個形參——這個指針的長度)blog
轉自:http://blog.csdn.net/kangroger/article/details/20653255io