繁体   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