#include <stdio.h>
#include <string.h>
void main()
{
char array[]="hello";
printf("%s",array[0]);
printf("%c",array[0]);
}
使用 %s 时无法访问数组[0],但使用 %c 时可以访问数组[0],帮我找到解决办法。
最佳答案
你应该在使用 %s 时使用地址 ==> &array[0]
因为 %s 需要一个指针作为参数。
通常我们使用
printf("%s",character_array_name);
这里character_array_name是第一个元素的地址
character_array_name == &character_array_name[0];
如果你只想打印一个字符,你需要使用
printf("%.1s",character_array_name);
示例代码:
#include<stdio.h>
int main()
{
char *str="Hello World";
printf("%s\n",str); //this prints entire string and will not modify the pointer location but prints till the occurence of Null.
printf("%.1s\n",str); //only one character will be printed
printf("%.2s\n",str); //only two characters will be printed
//initially str points to H in the "Hello World" string, now if you increment str location
str++; //try this str=str+3;
printf("%.1s\n",str); //only one character
printf("%.2s\n",str); //only two characters will be printed
str=str+5; //prints from the W
printf("%s\n",str); //this prints upto Hello because scanf treats space or null as end of strings
printf("%.1s\n",str); //only one character
printf("%.2s\n",str); //only two characters will be printed
return 0;
}
关于使用 %s 时无法访问数组的第一个下标,但可以使用 %c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18716379/