为什么函数不知道数组大小? [英] Why function does not know the array size?
本文介绍了为什么函数不知道数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我写
int main()
{
int a[100] = {1,2,3,4,};
cout<<sizeof(a)/sizeof(a[0])<<endl; //a is a pointer to the first elem of array,
//isn't it
return 0;
}
我得到400!
如果我写
void func(int * a);
void func(int *a);
int main()
{
int a[100] = {1,2,3,4,};
func(a);
return 0;
}
void func(int *a)
{
cout<<sizeof(a)/sizeof(a[0])<<endl; //a is a pointer to the first elem of array
}
那么,为什么函数不知道数组大小?
So why function does not know the array size?
推荐答案
这不工作,因为sizeof是在编译时计算的。该函数没有关于它的参数大小的信息(它只知道它指向一个内存地址)。
This isn't working because sizeof is calculated at compile-time. The function has no information about the size of its parameter (it only knows that it points to a memory address).
考虑使用STL向量,或者传入数组尺寸作为函数的参数。
Consider using an STL vector instead, or passing in array sizes as parameters to functions.
这是由Marcel Guzman在 http://stackoverflow.com/questions/720077/calculating-size-of-an-array !
This was answered by Marcel Guzman in http://stackoverflow.com/questions/720077/calculating-size-of-an-array!
这篇关于为什么函数不知道数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文