sizeof 运算符的问题 [英] problem with sizeof operator
问题描述
因为我想在函数中动态查找数组大小,所以我使用了 sizeof 运算符.但我得到了一些意想不到的结果.这是一个演示程序,向您展示我想做什么.
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result. here is one demo program to show you, what i want to do.
//------------------------------------------------------------------------------------------
#include <iostream>
void getSize(int *S1){
int S_size = sizeof S1/sizeof(int);
std::cout<<"array size(in function):"<<S_size<<std::endl;
}
int main(){
int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
getSize(S);
std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
return 0;
}
//------------------------------------------------------------------------------------------
编译命令:g++ demo1.cc -o demo1 {fedora 12}
compilation command : g++ demo1.cc -o demo1 {fedora 12}
输出:
array size(in function):2
array size:19
<小时>
请解释,为什么会这样.可以做些什么来解决这个问题.
please explain ,why this is happening. what can be done to solve this problem.
推荐答案
void getSize(int *S1)
当你向这个函数传递一个数组时,它会衰减到pointer类型,所以sizeof
操作符将返回指针的大小.
When you pass an array to this function, it decays to pointer type, so sizeof
operator will return the size of pointer.
但是,您将函数定义为,
However, you define your function as,
template<int N>
void getSize(int (&S1)[N])
{
//N is the size of array
int S_size1 = N;
int S_size2 = sizeof(S1)/sizeof(int); //would be equal to N!!
std::cout<<"array size(in function):"<<S_size1<<std::endl;
std::cout<<"array size(in function):"<<S_size2<<std::endl;
}
int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
getSize(S); //same as before
那么你就可以在函数里得到数组的大小了!
then you can have the size of array, in the function!
在这里亲自观看演示:http://www.ideone.com/iGXNU
这篇关于sizeof 运算符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!