博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux 编程,C 语言中的陷阱 - sizeof(字符串字面量)
阅读量:4110 次
发布时间:2019-05-25

本文共 1846 字,大约阅读时间需要 6 分钟。

目录
  1. sizeof 运算符 / C 语言字符串字面量(计算字符串字面量长度时,会计入字符串结尾的空字符 ‘\0’)

1. sizeof 运算符
  • C 语言中的 字符串字面量作为字符数组来处理
  • 当 C 语言编译器在程序中遇到长度为 n 的字符串字面量时,会为字符串字面量分配长度为 n + 1 的内存空间。这块内存空间将用来存储字符串字面量中的字符,以及一个用来标志字符串末尾的额外字符(空字符,‘\0’)
  • 空字符是一个所有位都为 0 的字节,用转义字符 ‘\0’ 表示
  1. 实验代码如下(单目运算符 sizeof 在计算字符串长度时,会将字符串结尾的空字符(如果有的话)一并计入总长度):
#include 
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.cubuntu@cuname:~/dev/beginning-linux-programming/test$ ./test4a size is : 2 //b size is : 4c size is : 8
  1. 写文件操作时,写入字符串字面量末尾的空字符会导致文件输出混乱。代码如下:
#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 文件(显示正常,空字符被忽略了):

Linux 终端查看文件
使用 vscode 查看 error_code.txt 文件(异常输出):
使用 vscode 查看文本
使用 notepad++ 查看 error_code.txt 文件(异常输出):
使用 notepad++ 查看文件
使用 notepad 查看 error_code.txt 文件(非预期,notepad 将空字符解析为空格):
使用 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/

你可能感兴趣的文章
Container With Most Water --装最多水的容器(重)
查看>>
Longest Common Prefix -最长公共前缀
查看>>
Letter Combinations of a Phone Number
查看>>
Single Number II --出现一次的数(重)
查看>>
Valid Parentheses --括号匹配
查看>>
Generate Parentheses--生成匹配括号(重)
查看>>
Remove Element--原地移除重复元素
查看>>
Remove Duplicates from Sorted Array--从有序数组中移除重复元素
查看>>
Count and Say
查看>>
Gas Station
查看>>
Palindrome Partitioning --回文切割 深搜(重重)
查看>>
Valid Palindrome 简单的回文判断
查看>>
Pascal's Triangle -- 生成杨辉三角
查看>>
Pascal's Triangle II 生成杨辉三角中的某行
查看>>
Minimum Depth of Binary Tree -- 二叉树的最小深度 DFS 加剪枝
查看>>
Climbing Stairs 爬楼梯方法 动态规划
查看>>
Merge Two Sorted Lists 合并两个有序链表
查看>>
pow(x,n) 为什么错这么多次
查看>>
Jump Game 动态规划
查看>>
Binary Tree Maximum Path Sum 自底向上求解(重重重重)
查看>>