目录
- sizeof 运算符 / C 语言字符串字面量(计算字符串字面量长度时,会计入字符串结尾的空字符 ‘\0’)
1. sizeof 运算符
- C 语言中的 字符串字面量作为字符数组来处理
- 当 C 语言编译器在程序中遇到长度为 n 的字符串字面量时,会为字符串字面量分配长度为 n + 1 的内存空间。这块内存空间将用来存储字符串字面量中的字符,以及一个用来标志字符串末尾的额外字符(空字符,‘\0’)
- 空字符是一个所有位都为 0 的字节,用转义字符 ‘\0’ 表示
- 实验代码如下(单目运算符 sizeof 在计算字符串长度时,会将字符串结尾的空字符(如果有的话)一并计入总长度):
#include <stdio.h>
void main(){
char a[] = "a"; // 默认使用 2 个字节存储变量 a 的数据,即:['a']['\0']
printf("a size is : %ld\n", sizeof(a)); //
char b[4] = "4444";
printf("b size is : %ld\n", sizeof(b)); // 打印数组 b 的长度,b 的声明长度为 4
char c[8] = "8";
printf("c size is : %ld\n", sizeof(c)); // 打印数组 c 的长度,c 的声明长度为 8
}
执行结果如下:
ubuntu@cuname:~/dev/beginning-linux-programming/test$ gcc -o test4 test4.c
ubuntu@cuname:~/dev/beginning-linux-programming/test$ ./test4
a size is : 2 //
b size is : 4
c size is : 8
- 写文件操作时,写入字符串字面量末尾的空字符会导致文件输出混乱。代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void main(){
int de = open("error_code.txt", O_WRONLY | O_CREAT | O_TRUNC);
char a[] = "hi\n";
char b[] = "this world.\n";
write(de, a, sizeof(a)); // 没有排除字符串字面量末尾的空字符
write(de, b, sizeof(b)); // 没有排除字符串字面量末尾的空字符
close(de);
}
使用 Linux 终端查看 error_code.txt 文件(显示正常,空字符被忽略了):
使用 vscode 查看 error_code.txt 文件(异常输出):
使用 notepad++ 查看 error_code.txt 文件(异常输出):
使用 notepad 查看 error_code.txt 文件(非预期,notepad 将空字符解析为空格):
可以发现 使用不同的工具查看,会有不同的 ‘解释’ 。
将上述程序代码修改为(写入时去掉字符串字面量末尾的空字符):
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void main(){
int de = open("error_code.txt", O_WRONLY | O_CREAT | O_TRUNC);
char a[] = "hi\n";
char b[] = "this world.\n";
write(de, a, sizeof(a) - 1); // 去掉字符串字面量末尾的空字符
write(de, b, sizeof(b) - 1); // 去掉字符串字面量末尾的空字符
close(de);
}
执行后,输出结果正确(这才是我想要的呀: ):