首页 > 解决方案 > C:返回 D 作为输出,为什么?

问题描述

#include <stdio.h>

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

我用 C 编写了一个小代码。在此代码的最后一条语句中,我%c在函数中使用格式说明符printf()并分配其中命名s的指针。它给我D作为输出。它是返回垃圾值还是我的代码自动在其中分配 ASCII 值或其他东西?

当我添加s+1它时返回Es+2返回F等等。谁能澄清我?

标签: cstringpointers

解决方案


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

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

推荐阅读