簡體   English   中英

以下 C 代碼的輸出是什么?

[英]What will be the output of the following C code?

#include <stdio.h>

int *m() {
    int *p = 5;
    return p;
}

void main() {
    int *k = m();
    printf("%d", k);
}

答案來了5 有人可以解釋一下答案是如何來的5嗎? 我試圖解決它,但無法理解它是如何工作的。

當您使用錯誤的 printf 格式時,這里有一個 UB。

如果您將其顯式轉換為int代碼將 100% 正確,但如果指針和整數具有不同的大小,則並非指針的每個值都將被正確轉換。

您還需要將整數轉換為指針以抑制警告。

#include <stdio.h>

int *m()
{
    int *p = (int *)5;   // conversion of the integer 5 to the pointer
    return p;
}

int main(void)
{
    int *k = m();
    printf("%d", (int)k);  // conversion of the pointers (keeping the
           // converted integer value of 5) back to the integer value.
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM