[C语言]关于指针和int型的一道题目
题目就下面几行,问printf的输出是什么?
1 2 3 4 5 6 7 | int main() { unsigned int a[3] = {0x010203, 0x040506, 0x070809}; unsigned int *b0 = (unsigned int *)( ( int )a + 1); printf ( "%x\n" , *b0); return 0; } |
在某个论坛上看到这个问题,展开讨论以后,其涉及到了不少的C语言知识。各位先不妨自己想想你自己的答案是什么。
--------------------------------------------------------分割线-------------------------------------------
在VS2008下,输出是6000102。原因如下:
a[3]数组在内存中的存储方式如下
低地址-------------------------------->高地址
03 02 01 00 06 05 04 00 09 08 07 00
^^^^^^^^
b0指向这里
所以printf打印出来的值是6000102
也许大部分的面试,问到这里估计就结束了,可以得满分了。
不过在我看来,顶多能得30分。
很明显这个题的是一个编译器实现相关的问题。还应该考虑些什么呢?
1.大小端的问题。在大端机器上,可能的答案是1020300
2.32bits或64bits地址的问题,如果是64bits地址和32bits整形(int)的话,很明显(int)a这句话就会有问题了
3.int的大小一定是32bits吗?当然不是了,C99标准中如下说
5.2.4.2.1Sizes of integer types <limits.h>
...
Their implementation-defined values shall be equal or greater in magnitude (absolutevalue) to those shown, with the same sign.
...
—maximum value for an object of type unsigned int
UINT_MAX65535 // 2^16 - 1
4. unsigned int *b0 = (unsigned int*)((int)a + 1);这句话真的是安全的吗?
必然不是的,整个这个语句就是一个implementation-defined的,C99标准如下说
An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be atrap representation.
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
假设我是面试官的话,能答出大小端和64bits,就是蛮不错的了
至于答出第3,4点就比较困难了,会阅读C99标准的应该不多。
标准中是否还有其他和这个题相关,我也不知道,我也没有通读C99标准。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述