【问题标题】:Unexpected output in C program when printing打印时 C 程序中的意外输出
【发布时间】:2021-10-12 19:33:51
【问题描述】:

假设所有头文件都包含在内。

void main() { 
int i; 
clrscr(); 
printf("india"-'A'+'B'); 
getch(); }

以下函数的输出为:ndia

谁能解释一下这个输出?

【问题讨论】:

  • 指针运算。你为什么不解释你的期望?
  • 表达式"india"-'A'+'B' 根本没有任何意义
  • @klutt 似乎更像是测验或类似问题上的一个技巧问题。旨在混淆视听。

标签: c output printf


【解决方案1】:
int printf(const char *restrict format, ...);

当您执行 format - 'A' + 'B' 时,考虑到 AB 的 ASCII 值,它等于 format + 1

format 是基地址,当您执行format + 1 时,它指向该字符串的第二个内存位置,并从那里开始打印ndia

【讨论】:

    【解决方案2】:

    表达式"india"-'A'+'B' 在任何健全的代码中都没有意义。但它会(但见下文)导致指向第二个元素的指针,因为'B' - 'A' 将评估为1

    但是,子表达式"india"-'A' 将调用未定义的行为,因为结果指针将指向数组之外。这在这里解释:Why is pointing to one before the first element of an array not allowed in C?

    如果我们稍微改写一下并添加括号:"india"+('B'-'A'),表达式定义明确,等于"india" + 1

    【讨论】:

    • 表达式 printf("india"-('A'+'B')) 指向 {A(65)+B(66)} 的 "india"-131 ASCII 并且此表达式 @987654329 没有输出@ .但是表达式printf("india"+(-'A'+'B')) 打印出:ndia
    • @AdityaMishra 不知道为什么我的评论消失了,但是谢谢。我已经解决了这些问题。
    猜你喜欢
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多