【C语言】那些关于字符串的事

一、字符串崩溃的原因:1、试图修改字符串常量的值;2、越界

eg:

char *str1 = "abcde" ; //这里是字符串常量 (不能被修改)
char str2[] = "abcde" ; //字符数组,包括'\0'也是字符串
str1[0] = 'x'; //error 作为一个字符串常量只有读权限,没有写权限
str2[0] = 'x'; //ok

strcpy(str1 , "xyz"); //error 作为一个字符串常量只有读权限,没有写权限

strcpy(str2 , "hello world"); //error 越界

二、字符串

//字符串
#include <stdio.h>
#include <string.h>

int main()
{
	char str1[100] = "abcde";//100 , 5
	char str2[] = "abcde";//6 , 5
	char str3[100] = "abcdef\0ijka\n";//100 , 6
	char str4[] = "abcdef\0ijka\n";//13(最后还有一个'\0') ,6
	char *str5 = "abcde";//4(指针长度都为 4), 5
	char *str6 = "abcdef\0ijka\n";//4 , 6
	printf ("%6d%6d\n",sizeof(str1),strlen(str1));//strlen统计str字符串的字符个数,不包括 '\0' 
	printf ("%6d%6d\n",sizeof(str2),strlen(str2));
	printf ("%6d%6d\n",sizeof(str3),strlen(str3));
	printf ("%6d%6d\n",sizeof(str4),strlen(str4));
	printf ("%6d%6d\n",sizeof(str5),strlen(str5));
	printf ("%6d%6d\n",sizeof(str6),strlen(str6));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41576955/article/details/79904996