2014-10-10 102 views
0

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

这是我的代码:

int main(void) { 

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

    return 0; 
} 

我不是舒尔如果这是一个字符串用C是如何工作的,所以如果你有一些建议,请帮助。

+6

在printf的打印字符串的任何字符对单个字符使用'%c','%s'用于字符串。 – jpw 2014-10-10 00:19:59

+0

@jpw - 谢谢!你从一些非常恐怖中拯救了我:D! – 2014-10-10 00:27:44

+0

您在下面评论过您使用的是在线编译器。为什么不下载完整的MinGW C/C++编译器。它免费提供。 – ryyker 2014-10-10 00:35:48

回答

0

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

在这里,在您的代码str串是这样的:

char str[] = "Hello"; 

STR [0] = 'H'
STR [1] = 'E'
STR [2] =“升“
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); 
1

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

printf("%c \n", str[0]); 

打印整个字符串,你需要使用%S

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

,你会得到你的代码warning,所以留心听警告

warning: format '%s' expects argument of type 'char*', but argument 2 has type 'int' [-Wf 
ormat=]                         
    printf("%s\n", str[0]);  
+0

Rajesh - 信息的ty。不幸的是,我使用了一个在线编译器,除了正常的运行时错误外,没有给我任何东西。:(! – 2014-10-10 00:29:36

+0

尝试https://www.sourcelair.com,它具有很好的linux控制台界面,它不是促销活动,我经常使用它。 – radar 2014-10-10 00:44:07

0

您必须使用"%c"选项用printf打印单个字符,"%s"用于字符串。在你的例子中你会得到分段错误。与

gcc -Os -Wall -pedantic main.c && ./a.out 

编译程序发出严格的ISO C和ISO C要求的所有警告++ &拒绝所有使用禁止扩展名的程序。这将产生一个警告:

警告:格式 '%s' 的期望类型 '字符*' 的参数,但参数2 具有类型 'INT'[-Wformat =] 的printf(“%S \ n “,str [0]);

http://coliru.stacked-crooked.com/a/a56055e381c209f1

0

这可能会帮助你的结果预计:

int main(void) { 

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

char *str = "Hello"; 

/*changed from %s to %c 
*/ 

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

return 0; 

}

这将打印字符长度的第一变量由乙方指向。

相关问题