C:为什么将 D 作为输出返回? [英] C: Returning D as output why?

查看:55
本文介绍了C:为什么将 D 作为输出返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main(){
    char *s="hello world";
    printf("%c\n",s);
}

我用 C 写了一小段代码.在这段代码的最后一条语句中,我在 printf() 函数中使用了 %c 格式说明符并分配了名为s 在里面.它给了我 D 作为输出.它是返回垃圾值还是我的代码自动在其中分配 ASCII 值或其他什么?

I have written a small code in C. In last statement of this code I'm using %c format-specifier in printf() function and assigning pointer named s in it. It is giving me D as output. Does it is returning garbage value or does my code automatically assigning ASCII value in it or something else?

当我添加 s+1 它返回 Es+2 返回 F 等等.谁能帮我解释一下?

When I add s+1 it return E and s+2 return F and so on. Can anyone clarify me?

推荐答案

%c 打印 char,而不是字符串.由于您的变量 s 不是 char,而是指向 char 的指针,printf 将地址解释为你的字符串作为一个字符.您可能想使用其中一个片段:

%c prints a char, not a string. Since your variable s is not a char, but rather a pointer to a char, printf interprets the address to your string as a character. You probably want to use one of the snippets:

printf("%c\n", s[0]); // print the first character in your string
printf("%s\n", s); // print the whole string

这篇关于C:为什么将 D 作为输出返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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