定义
#include <stdio.h>
void main()
{
char a[5]={'a','b','c','d','e'};
printf("%c",a[0]);
}
int b[5]={'A','B', 'C','D','E'};
char a[5]={'A','B', 'C','D','E'};
for(i=0;i<5;i++)
{
printf("%d",b[i]); //65 66 67 68 69 70
printf("%c",b[i]); //A B C D E
printf("%d",A[i]); //65 66 67 68 69 70
printf("%c",A[i]); //A B C D E
}
#include <stdio.h>
void main()
{
int i;
int b[5]={'A','B', 'C','D','E'};
char A[5]={1,'B', 'C','D','E'};
printf("%d\n",sizeof(b[0]));//4
printf("%d",sizeof(A[0]));//1
}
初始化
- 如果字符长度超出数组长度,错误
-
如果字符长度小于数组长度,只将前面经行赋值,其余为’\0’
-
如果字符长度与数组长度相同时,
字符串数组
- 用字符数组来存放一个字符串
- 遇见\0就结束
初始化
#include <stdio.h>
void main()
{
int i;
char b[]={"hello"};
char a[]="hello";
}
#include <stdio.h>
void main()
{
int i;
char b[]={"hello"};
char a[]={'h','e','l','l','o','\n'};//与b相同
}
- 超出
- 少于
#include <stdio.h>
void main()
{
int i;
char b[10]={"hello"};
printf("%s\n",b); //整体输出
for(i=0;b[i]!='\0';i++)
{
printf("%c",b[i]);//逐个输出
}
}
- 对于字符数组输入不需要加&
#include <stdio.h>
void main()
{
int i;
char b[100];//char b[]错误
scanf("%s",b);
}
- 在计算长度时
- stelrn 实际长度
- sizeof 包括/0
#include <stdio.h>
#include<string.h>
void main()
{
int i;
char b[]="chine";
printf("%d\n",sizeof(b));//6
printf("%d",strlen(b));//5
}