C语言入门——字符数组

定义

#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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值