Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中字符串的第一个字母_C_String_Printf - Fatal编程技术网

C中字符串的第一个字母

C中字符串的第一个字母,c,string,printf,C,String,Printf,我想打印字符串的第一个字母,但出现运行时错误 这是我的代码: int main(void) { char str[] = "Hello"; printf("%s\n", str[0]); return 0; } 如果这是C语言中字符串的工作方式,我不是舒尔,因此如果您有一些建议,请提供帮助。您应该使用%C打印单个字符 printf("%c \n", str[0]); 要打印整个字符串,您需要使用%s printf("%s\n", str); 您的代码

我想打印字符串的第一个字母,但出现运行时错误

这是我的代码:

int main(void) {

    char str[] = "Hello";
    printf("%s\n", str[0]);

    return 0;
}

如果这是C语言中字符串的工作方式,我不是舒尔,因此如果您有一些建议,请提供帮助。

您应该使用
%C
打印单个字符

   printf("%c \n", str[0]);
要打印整个字符串,您需要使用%s

   printf("%s\n", str);
您的代码会出现
警告
,因此请注意警告

warning: format '%s' expects argument of type 'char*', but argument 2 has type 'int' [-Wf
ormat=]                                                                                                  
     printf("%s\n", str[0]);      
您必须使用
%c”
选项打印带有
printf
的单个字符,
%s”
用于字符串。在您的示例中,您将遇到分段错误。使用

gcc -Os -Wall -pedantic main.c &&  ./a.out
发布严格ISO和ISO C++要求的所有警告,拒绝使用禁止扩展的所有程序。这将产生一个警告:

警告:格式“%s”要求参数类型为“char*”,但参数类型为2 具有类型“int”[-Wformat=] printf(“%s\n”,str[0])


这可能有助于获得预期的结果:

int main(void) {

/*changed from str[] to *str 
*/

char *str = "Hello";

/*changed from %s to %c
*/

printf("%c\n", str);

return 0;
}


这将打印str指向的第一个字符长度变量。

C字符串是以0字节结尾的一系列字符,也称为以null结尾的字符串。它可以作为数组(char[])或作为指向第一个字符(char*)的指针进行访问。
注意:数组总是从0索引位置开始

在您的代码
str
字符串中,如下所示:

char str[] = "Hello";
str[0]=“H”
str[1]=“e”
str[2]=“l”
str[3]=“l”
str[4]=“o”
str[5]='\0'

因此,只需使用
printf

    printf( "%c",str[0] ); // for the first, changing the value if number you can change the position of character to be printed


您使用了用于打印整个字符串的
%s

   printf( "%s",str );

在printf中,使用
%c
表示单个字符,
%s
表示字符串。@jpw-谢谢!你把我从某种可怕的事情中救了出来:D!您在下面评论说您正在使用在线编译器。为什么不下载完整的mingwc/C++编译器呢。它是免费提供的。Rajesh-ty的信息。遗憾的是,我使用了一个在线编译器,除了一个正常的运行时错误外,它什么也没有给我:(!试试看,它有很好的linux控制台界面。这不是一个升级,我经常使用它。