为什么在C中使用printf时会出现奇怪的输出? [英] Why am I Strange Output when using printf in C?

查看:94
本文介绍了为什么在C中使用printf时会出现奇怪的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究这个问题:

I've been working on this problem:

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

为什么要打印《早晨》?

Why does this print Morning?

有什么解释吗?

推荐答案

在此printf调用中

In this call of printf

printf(5 + "Good Morning ");

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

there is used the string literal "Good Morning " that has the type char[14]. Used in the expression 5 + "Good Morning " it is converted to a pointer to its first character and has the type char *.

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

So due to the pointer arithmetic the expression having the type char * points to the element of the string literal at the position equal to 5 (positions start from 0). That is it points to the substring "Morning " of the original string literal. And that substring is outputted.

您可以通过以下方式等效地重写通话,以使其更加清晰

You could equivalently rewrite the call the following way to make it more clear

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

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

甚至喜欢

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

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

Here is a demonstrative program but instead of printf I am using 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 
 

这篇关于为什么在C中使用printf时会出现奇怪的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆