在C语言中,我们经常用如下两种方式来表示字符串:
char *string = "hello world";
char string[] = "hello world";
可能有时还会用这种方式:
char string[11] = "hello world";
问题来了,他们一样吗?不一样的话有什么不同?
我用如下代码来做测试:
#include<stdio.h>
#include<string.h>
int main(void)
{
int i;
char *str1 = "hello world";
char str2[] = "hello world";
char str3[11] = "hello world";
printf("sizeof: %4lu%4lu%4lu\n", sizeof(str1), sizeof(str2), sizeof(str3));
printf("strlen: %4lu%4lu%4lu\n", strlen(str1), strlen(str2), strlen(str3));
printf("str1[12]=%d\n", str1[12]);
printf("str2[12]=%d\n", str2[12]);
printf("str3[12]=%d\n", str3[12]);
printf("*str1=%s\n", str1);
printf("str2[]=%s\n", str2);
printf("str3[11]=%s\n", str3);
return 0;
}
用gcc编译后输出如下:
sizeof: 8 12 11
strlen: 11 11 11
str1[12]=115
str2[12]=0
str3[12]=0
*str1=hello world
str2[]=hello world
str3[11]=hello world
分析:
str1的长度为8,修改字符串的字度后仍然为8,说明这个长度是指针的长度,和字符串没有关系,所以str1的意思就是指向字符串的指针。不能有“str1[0] = ‘H’;”这样的写法,即不能修改字符串的内容,运行时会报“Segmentation fault”错误。
str2的长度为12,因为编译器在最后自动添加了‘\0’,打印str2[12]可以看到该值。
str3的长度为11,这是字符数组的长度,用printf输出时有时正常输出,有时后面会有些乱码,那是因为str3[12]如果正好是‘\0’就正常,如果是其他值就会乱码。
综上,在c语言中用char []做字符串是最好的。