在 C 语言中,字符串实际上是使用空字符 \0 结尾的一维字符数组。因此,\0 是用于标记字符串的结束。
一、字符串&数组
void base_str() {
// 字符串数组和字符串指针
char str[] = "hello";
char str2[STR_LEN + 1] = "hello";
char str3[] = {'h', 'e', 'l', 'l', 'o'}; // 这种情况的数组没有办法当作字符串使用,因为没有'\0'
char str4[] = {'h', 'e', 'l', 'l', 'o', '\0'};
char *str5 = "hello";
printf("%lu, %lu\n", sizeof(str) / sizeof(char), strlen(str)); // 6, 5
printf("%lu, %lu\n", sizeof(str2) / sizeof(char), strlen(str2)); // 6, 5
printf("%lu, %lu\n", sizeof(str3) / sizeof(char), strlen(str3)); // 5, 10 这个10是因为遇到str4的'\0'
printf("%lu, %lu\n", sizeof(str4) / sizeof(char), strlen(str4)); // 6, 5
printf("%lu\n", strlen(str5)); // 5
// 下面两种写法存储方式大有不同,一个是二维数组,一个是指针数组,存储空间不同
char week[][10] = {"Monday", "Tuesday", " Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
char *week2[] = {"Monday", "Tuesday", " Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
printf("sizeof(week1) %lu\n", sizeof(week)); // 70
printf("sizeof(week2) %lu\n", sizeof(week2)); // 56
}