本文共 1846 字,大约阅读时间需要 6 分钟。
#includevoid 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.cubuntu@cuname:~/dev/beginning-linux-programming/test$ ./test4a size is : 2 //b size is : 4c size is : 8
#include#include #include #include #include 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#include #include #include #include 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);}
执行后,输出结果正确(这才是我想要的呀: ):
转载地址:http://iclsi.baihongyu.com/