博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
sizeof那道笔试题的秘密
阅读量:7118 次
发布时间:2019-06-28

本文共 2259 字,大约阅读时间需要 7 分钟。

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


【笔试题】:

请写出一个宏,计算数组的元素个数。   #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 
   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运算符不能返回动态分配的数组或外部的数组的大小。

本文转自 Jhuster 51CTO博客,原文链接:http://blog.51cto.com/ticktick/318727,如需转载请自行联系原作者

你可能感兴趣的文章
mysql中的事物处理
查看>>
Android 车联网天气
查看>>
POJ 2430 状压DP
查看>>
C++Primer第5版学习笔记(三)
查看>>
Centos7系统介绍
查看>>
GIT简单实用
查看>>
Sonar - 部署常见问题及解决方法
查看>>
IOS 学习笔记(3) 视图UITabbarController
查看>>
java基础知识(一)
查看>>
浏览器的缓存
查看>>
WinForm Read Excel
查看>>
Linux时间子系统之六:高精度定时器(HRTIMER)的原理和实现
查看>>
React开发环境搭建
查看>>
jQuery-ui源代码重点难点分析
查看>>
(转)Linux传输大文件(分割传输)
查看>>
1003. 我要通过!(20)
查看>>
phpstudy for linux版环境安装
查看>>
MinGW GCC 7.1.0 2017年6月份出炉啦
查看>>
二叉树的实现(Java语言描述)
查看>>
Json Datable Convert
查看>>