为什么以下代码的输出是25448
Why is the output of following code comes 25448?
当我尝试运行此代码时,它会给出以下输出:
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
中没有使用任何东西,为什么要包含它?不要同时包含iostream
和stdio.h
。在C++中更喜欢iostream
,因为它更安全。如果需要,使用cstdio
而不是stdio.h
你不应该同时标记C和C++。它们是不同的语言
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 为什么以下代码的输出是25448