用sizeof操作符的问题 [英] problem with sizeof operator

查看:117
本文介绍了用sizeof操作符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我想在动态函数找到数组的大小,我用sizeof操作符。但我得到了一些意想不到的结果。
这里一个演示程序告诉你,我想做的事情。

<$p$p><$c$c>//------------------------------------------------------------------------------------------
#包括LT&;&iostream的GT;无效的getSize(INT * S1){    INT S_size = sizeof的S1 /的sizeof(int)的;
    性病::法院LT&;&LT;数组大小(功能):&LT;&LT; S_size&LT;&LT;的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);
    性病::法院LT&;&LT;数组的大小:&LT;&LT; sizeof的S /的sizeof(int)的&LT;&LT;的std :: ENDL;
    返回0;
}
// ------------------------------------------------ ------------------------------------------

编译命令:G ++ demo1.cc -o demo1的{Fedora 12的}

输出:

 数组大小(功能):2
数组大小:19


请解释一下,为什么发生这种情况。
可以做些什么来解决这个问题。


解决方案

 无效的getSize(INT * S1)

当你传递一个数组到这个功能,它衰变到的指针的类型,所以的sizeof 运算符将返回指针的大小。

不过,你定义的功能,

 模板&LT; INT N'GT;
空隙的getSize(中间体(安培; S1),[N])
{
   // N是数组的大小
   INT S_size1 = N;
   INT S_size2 = sizeof的(S1)/的sizeof(int);在//将等于N!
   性病::法院LT&;&LT;数组大小(功能):&LT;&LT; S_size1&LT;&LT;的std :: ENDL;
   性病::法院LT&;&LT;数组大小(功能):&LT;&LT; S_size2&LT;&LT;的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); //和之前一样

那么你可以有数组的大小,在功能!

查看演示自己的位置: http://www.ideone.com/iGXNU

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;
}
//------------------------------------------------------------------------------------------

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

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)

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!

See the demonstration yourself here : http://www.ideone.com/iGXNU

这篇关于用sizeof操作符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆