sizeof运算符的问题

Whi*_*arf 4 c++ arrays sizeof

由于我想在函数中动态找到数组大小,我使用了sizeof运算符.但我有一些意想不到的结果.这是一个演示程序,向您展示,我想做什么.

//------------------------------------------------------------------------------------------
#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;
}
//------------------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

编译命令:g ++ demo1.cc -o demo1 {fedora 12}

输出:

array size(in function):2
array size:19
Run Code Online (Sandbox Code Playgroud)

请解释一下,为什么会这样.可以做些什么来解决这个问题.

Naw*_*waz 9

void getSize(int *S1)
Run Code Online (Sandbox Code Playgroud)

当您将数组传递给此函数时,它会衰减到指针类型,因此sizeof运算符将返回指针的大小.

但是,您将函数定义为,

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
Run Code Online (Sandbox Code Playgroud)

那么你可以在函数中拥有数组的大小!

请在此处查看演示:http://www.ideone.com/iGXNU