日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[C语言]关于指针和int型的一道题目

發布時間:2024/1/17 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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型的一道题目的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。