[C]关于%s,%c的字符串和数组

Han*_*Wui -3 c string printf

为什么我应该在这里使用%c而不是%s?如果我使用%s将错误

printf("%c",Array[i]);
Run Code Online (Sandbox Code Playgroud)

当我定义 char Array[STRSIZE]="apple"; should use %s here

那么如何正确使用%s和%c?

码:

#include<stdio.h>
#include<string.h>
   int main(){
      #define STRSIZE 81

         char Array[STRSIZE];
         printf("Enter a string: ");
         gets(Array);
         printf("\nYou entered: ");
         int i ;
    for(i=0;i<strlen(Array);i++){

         printf("%c",Array[i]);
    }
   return 0 ;} 
Run Code Online (Sandbox Code Playgroud)

结果:

Enter a string: apple
You entered: apple
Run Code Online (Sandbox Code Playgroud)

Bla*_*aze 6

%c打印一个char.%s打印一个字符串,所以它需要一个指向a的指针char.

char Array[STRSIZE];
Run Code Online (Sandbox Code Playgroud)

这里Array是一个数组char,所以Array传递给函数的表达式衰减到指针char.所以它可以用于%s(假设字符串有效).

Array[i]但是,它不是一个字符串.它是一个char,因此它可以传递%c,但不是%s.所以可能性是:

  • 打印一个字符串 printf("%s",Array);
  • 打印该字符串的单个字符printf("%c",Array[i]);.通过遍历字符串,您也可以像这样打印整个字符串