您的位置:首页 > 其它

sizeof那道笔试题的秘密

2010-05-21 08:42 274 查看

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


【笔试题】:


请写出一个宏,计算数组的元素个数。     #define countof(arr) ...     例如: int a[10], float b[20], char c[100]     调用:   countof(a),返回值为10   countof(b),返回值为20   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位操作系统)。


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


#include <iostream>     int getNum(void *pArr)   {       return sizeof(pArr);   }     int _tmain(int argc, _TCHAR* argv[])   {       /** 本测试说明:sizeof操作符作用于静态数组时返回整个数组的全部存储字节数 */        int myArr[10];       std::cout << "sizeof(int): " << sizeof(int) << std::endl;       std::cout << "myArr : " << sizeof(myArr) << std::endl;         /** 本测试说明:sizeof操作符不能返回动态分配的数组的字节数 */        int *pTest = new int(10);       std::cout << "pTest : " << sizeof(pTest) << std::endl;         /** 本测试说明:sizeof计算形参得到的结果 —— 指针类型的字节数 */        int myParam[10];       char myChar[10];       std::cout << "getNum(myParam) :" << getNum(myParam) << std::endl;       std::cout << "getNum(myChar ) :" << getNum(myChar) << std::endl;         getchar();       getchar();         return 0;   }

【结果】:sizeof(int): 4   myArr : 40   pTest : 4   getNum(myParam) :4   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运算符不能返回动态分配的数组或外部的数组的大小。


阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: