sizeof那道笔试题的秘密

最近做了一套软件公司的笔试题,其中有一题要求给定数组名,求数组的元素个数,当时没有做出来,后来仔细思考和分析了一番,有了一些新的收获,分享于此~~

【笔试题】:

 
 
  1. 请写出一个宏,计算数组的元素个数。  
  2.  
  3. #define countof(arr) ...  
  4.  
  5. 例如: int a[10], float b[20], char c[100]  
  6.  
  7. 调用:  
  8. countof(a),返回值为10  
  9. countof(b),返回值为20  
  10. countof(c),返回值为100  

【答案】: #define countof(arr) sizeof(arr)/sizeof(arr[0])

【小问题】:大家知道为什么试题要求写一个宏,而不是要求写一个类似下面的一个函数呢?

int countof(void *arr)
{
    
}
大家可以测试一下,如果在上面这个函数中实现return sizeof(arr)/sizeof(arr[0]),我们能不能达到最终的期望结果?

---------------------------------------------------------
看下面答案前请大家先思考几分钟
---------------------------------------------------------

【答案】:不能实现,因为sizeof是在编译时计算结果,而不支持在运行时计算结果,因此,如果在函数中写入sizeof(arr),该句子只会返回指针类型所占用的字节数,即4个字节(32位操作系统)。


【测试练习】,大家看看下面这段代码的输出结果是什么?

 
 
  1. #include <iostream>  
  2.  
  3. int getNum(void *pArr)  
  4. {  
  5.     return sizeof(pArr);  
  6. }  
  7.  
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.     /** 本测试说明:sizeof操作符作用于静态数组时返回整个数组的全部存储字节数 */   
  11.     int myArr[10];  
  12.     std::cout << "sizeof(int): " << sizeof(int) << std::endl;  
  13.     std::cout << "myArr : " << sizeof(myArr) << std::endl;  
  14.  
  15.     /** 本测试说明:sizeof操作符不能返回动态分配的数组的字节数 */   
  16.     int *pTest = new int(10);  
  17.     std::cout << "pTest : " << sizeof(pTest) << std::endl;  
  18.  
  19.     /** 本测试说明:sizeof计算形参得到的结果 —— 指针类型的字节数 */   
  20.     int myParam[10];  
  21.     char myChar[10];  
  22.     std::cout << "getNum(myParam) :" << getNum(myParam) << std::endl;  
  23.     std::cout << "getNum(myChar ) :" << getNum(myChar) << std::endl;  
  24.  
  25.     getchar();  
  26.     getchar();  
  27.  
  28.     return 0;  

【结果】:

 
 
  1. sizeof(int): 4  
  2. myArr : 40  
  3. pTest : 4  
  4. getNum(myParam) :4  
  5. getNum(myChar ) :4 


【附】:

下面是sizeof的MSDN上的解释。

The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

sizeof关键词给出了存储传入的变量或者类型(包括聚合类型)所需要的字节数。该关键词返回size_t类型的变量。

When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

当应用到一个结构类型或变量,sizeof返回实际的大小,这可能包括为了字节对齐而填充的字节。当应用于静态维数组,sizeof返回整个数组的大小。 sizeof运算符不能返回动态分配的数组或外部的数组的大小。

 

 

本文出自 “对影成三人” 博客,请务必保留此出处http://ticktick.blog.51cto.com/823160/318727

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值