C++问题:在函数内计算数组大小,用了两种方法,为什么结果会不一样?

#include <iostream.h>
int popSort(int a[])
{
int n;
n=sizeof(a)/sizeof(int);
return n;
}
void main()
{
int n;
int a[]={10,2,3,4,1,6,7,8,9};
n=sizeof(a)/sizeof(int);
cout<<n<<" "<<popSort(a)<<endl;
}

数组传到函数int popSort(int a[])中退化为了一个指针,相当于int popSort(int *a)。
我这里倒是有一个办法保证能传数组,但是不知道你的编译器是否支持。注意下面的popSort2函数。

#include <iostream>

using namespace std;

int popSort(int a[])
{
int n;
n=sizeof(a)/sizeof(int);
return n;
}

template<size_t N>
size_t popSort2(int (&a)[N])
{
return N;
}

int main()
{
int n;
int a[]={10,2,3,4,1,6,7,8,9};
n=sizeof(a)/sizeof(int);
cout<<n<<" "<<popSort(a) << " " << popSort2(a) <<endl;

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-10-08
数组传到函数里,就成指针了。失去了数组的意义了。纯粹一个指针。追问

int popSort(int a[])

int popSort(int *a)
就是完全一样的了?

第2个回答  2019-09-17
数组是原始数据类型,程序运行时没有关于该数组大小的数据,编程者必须自己给出给数组的大小,是否越界等信息。
比如定义了一个数组后,编程者还必须定义一个单独的变量用来存储数组的大小,以确保访问数组不会越界。
所以不使用单独的变量,程序是不可能知道该数组的大小的。
sizeof(a)的结果不是数组的长度,而是指针int
*a的字节数。
相似回答