[C语言]关于指针和int型的一道题目
題目就下面幾行,問printf的輸出是什么?
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標準。
轉載于:https://www.cnblogs.com/aoaoblogs/archive/2010/10/16/1853313.html
總結
以上是生活随笔為你收集整理的[C语言]关于指针和int型的一道题目的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP_SELF、 SCRIPT_NAM
- 下一篇: WPF 放大镜(Magnifying G