轉載:http://blog.csdn.net/kangroger/article/details/20653255
在做這道題時:
32位環境下,int *p=new int[10];請問sizeof(p)的值為()
A、4 ? ? ? ? ? ? ?B、10 ? ? ? ? ? ? ?C、40 ? ? ? ? ? ? ? D、8
我以為正確答案為C,int類型為32位,占四個字節,10個自然就是40了,結果正確答案為A,只是指針p占的空間。
因此寫段代碼測試一下:
#include<iostream>
using namespace std;
void fun(int P[])//P這里作為指針使用
{
cout<<"在函數中"<<sizeof(P)<<endl;
}
int main()
{
int A[10];
int* B=new int[10];
cout<<"數組名"<<sizeof(A)<<endl;
cout<<"指針"<<sizeof(B)<<endl;
fun(A);
}
或者
#include<iostream>
using namespace std;
void fun(int *P)
{
cout<<"在函數中"<<sizeof(P)<<endl;
}
int main()
{
int A[10];
int* B=new int[10];
cout<<"數組名"<<sizeof(A)<<endl;
cout<<"指針"<<sizeof(B)<<endl;
fun(A);
}
以上結果均輸出:
數組名40
指針4
在函數中4
由此可見,數組名并不是完全等同于指針。雖然它們都可以通過指針方式訪問數組。
但是數組在作為函數參數傳遞過程中,會退化成指針。這也是為什么指針作為參數傳遞時,經常要一個長度。