使用 %s 时无法访问数组的第一个下标,但可以使用 %c

标签 c arrays char c-strings

#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/

相关文章:

c语言printf float错误

c - 在 MonoDevelop 中调试 C 应用程序失败

java - 使用java中的比较器对二维数组的每一列进行排序

javascript - JS中如何使用findIndex()查找所选项目的索引?

c - 为什么我能够在此 char 数组中存储的字节数比使用 malloc() 提供的字节数多?

C 循环中的 char 数组赋值?

c - 如何使用 scanf 从下一行输入数据中获取输入?

cmake ctest生成

sql - 快速构建源自 SQL 数据库的 Web 图表原型(prototype)的方法

c - 将二维数组传递给 C 中的 GTK 函数