[英]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.