为什么在 C 中使用 printf 时出现奇怪的输出?

问题描述

我一直在解决这个问题:

#include<stdio.h>
int main()
{
    printf(5 + "Good Morning ");
    return 0;
}

为什么会打印 Morning?

有什么解释吗?

解决方法

在 printf 的这个调用中

printf(5 + "Good Morning ");

使用了类型为 "Good Morning " 的字符串文字 char[14]。在表达式 5 + "Good Morning " 中使用,它被转换为指向其第一个字符的指针,类型为 char *

因此,由于指针算术的原因,char * 类型的表达式指向字符串文字的元素在等于 5 的位置(位置从 0 开始)。也就是说,它指向原始字符串文字的子字符串 "Morning "。然后输出那个子串。

您可以通过以下方式等效地重写调用以使其更清晰

char * literal = "Good Morning ";
printf( literal + 5 );

char * literal = "Good Morning ";
printf( &literal[5] );

甚至喜欢

printf( &"Good Morning "[5] );

这是一个演示程序,但我使用的是 printf 而不是 puts

#include <stdio.h>

int main(void) 
{
    size_t i = 0;
    
    while ( puts( i + "Good Morning " ) != 1 ) i++;

    return 0;
}

程序输出为

Good Morning 
ood Morning 
od Morning 
d Morning 
 Morning 
Morning 
orning 
rning 
ning 
ing 
ng 
g