为什么以下代码的输出是25448

Why is the output of following code comes 25448?

本文关键字:输出 25448 代码 为什么      更新时间:2023-10-16

当我尝试运行此代码时,它会给出以下输出:

c
99
25448
4636795

我想知道编译器是如何生成最后两个输出的?

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char ch='c';
    printf("%cn",ch);
    printf("%dn",ch);
    printf("%dn",'ch');
    printf("%d","ch");
    return 0;
}
printf("%c",ch);       - print normal character
printf("%dn",ch);     - print ascii value of character
printf("%dn",'ch');   - multi-character literal
printf("%d","ch");     - print value of pointer to string "ch"

关于"ch">

25448是0x6368,63是"c"的十六进制,68是"h"的十六进制

printf("%c", ch);     // print ch as a character
printf("%dn", ch);   // print the ASCII value of ch
printf("%dn", 'ch'); // print the value of the multi-character literal 'ch'
                      // implementation defined, but in this case 'ch' == 'c' << 8 | 'h'
printf("%d", "ch");   // print the address of the string literal "ch"
                      // undefined behavior, read below

关于多字符文字阅读这里

您的代码在最后一个printf中调用未定义的行为,因为您使用了错误的格式说明符。printf需要一个整数,而您正在传递一个地址。在64位系统中,这很可能是64位值,而int是32位。正确的版本应该是

printf("%p", (void*)"ch");

另一个问题是,你在iostream中没有使用任何东西,为什么要包含它?不要同时包含iostreamstdio.h。在C++中更喜欢iostream,因为它更安全。如果需要,使用cstdio而不是stdio.h

你不应该同时标记C和C++。它们是不同的语言