C語言基礎知識-數組(二)字符數組 -定义字符串的几种方式
一.定义字符串的几种方式
#include <stdio.h>
#include <stdlib.h>
void test1(void)
{
//定义字符串的几种方式
//字符串和字符数组的区别:最后一位是否是空字符
char buf[12]={"Monday"};
char buf1[]={'T','u','e','s','d','a','y'};
char buf2[12]={'W','e','d','n','e','s','d','a','y'};
char *p="Thursday";
printf("buf=%s %d\n", buf,sizeof(buf));
printf("buf1=%s %d\n", buf1,sizeof(buf1));
printf("buf2=%s %d\n", buf2,sizeof(buf2));
printf("p=%s %d\n", p,sizeof(p));
int len = strlen(buf), i;
//1每次输出一个字符
printf("1buf=");
for(i=0; i<len; i++)
{
printf("%c", buf[i]);
}
printf("\n");
char *pstr = buf;
//2使用*(pstr+i)
printf("2pstr=");
for(i=0; i<len; i++){
printf("%c", *(pstr+i));
}
printf("\n");
//3使用pstr[i]
printf("3pstr=");
for(i=0; i<len; i++){
printf("%c", pstr[i]);
}
printf("\n");
//4使用*(buf+i)
printf("4buf=");
for(i=0; i<len; i++){
printf("%c", *(buf+i));
}
printf("\n");
//5直接输出字符串p
printf("5p=%s\n", p);
//6使用*(p+i)
printf("6p=");
for(i=0; i<len; i++){
printf("%c", *(p+i));
}
printf("\n");
//7p[i]
printf("7p=");
for(i=0; i<len; i++){
printf("%c", p[i]);
}
printf("\n");
}
int main()
{
test1();
return 0;
}
/*
注意:
声明存储字符串的数组时,数组大小至少比所存储的字符串多1,因为编译器会自动在
字符串常量的末尾添加空字符\0
*/
輸出結果
buf=Monday 12
buf1=TuesdayMonday 7
buf2=Wednesday 12
p=Thursday 4
1buf=Monday
2pstr=Monday
3pstr=Monday
4buf=Monday
5p=Thursday
6p=Thursday
7p=Thursday
二。字符串傳參
#include <stdio.h>
void test(char a[5], char *b, char c[], char d[][10], char e[][8], char f[3][8])
{
printf("a %d \n",sizeof(a));//4
printf("b %d \n",sizeof(b));//4
printf("c %d \n",sizeof(c));//4
printf("d %d \n",sizeof(d));//4
printf("e %d \n",sizeof(e));//4
printf("f %d \n",sizeof(f));//4
printf("d1 %d \n",sizeof(d[1]));//10
printf("e1 %d \n",sizeof(e[1]));//8
printf("f1 %d \n",sizeof(f[1]));//8
}
void main(void)
{
char g[4][12];
char h[11];
test(h, h, h, g, g, g);
return 0;
}
/*
注意:
字符串傳參時不能帶入長度,abcedf的寫法皆為傳址,即指針占字節數4.
*/
輸出結果
a 4
b 4
c 4
d 4
e 4
f 4
d1 10
e1 8
f1 8
三。擴展
#include <stdio.h>
#define max_length 16
void test2(char *p,int length)
{
char value[129]="";
if (length > max_length)
{
printf("error:too long \n");
return 0;
}
else
{
strncpy(value, p, max_length);
printf("p=%s \n", p);
printf("value=%s \n",value);
}
}
void main(void)
{
char buf[]={"MondayTuesdayWednesdayThursday"};
char buf2[12]={'W','e','d','n','e','s','d','a','y'};
test2(buf,sizeof(buf));
test2(buf2,sizeof(buf2));
char * keyWord[6] = {"eagle", "cat", "and", "dog", "ball", NULL};
return 0;
}
輸出結果
error:too long
p=Wednesday
value=Wednesday