InfoCode

C++ · 字符串

字符数组及相关函数

区分 C++ 字符数组的字符串长度与缓冲区容量,理解结束符和拼接空间,避免越界与未终止字符串。

InfoCode 编写 · 技术参考见下文

在应用中练这个知识点 在应用中阅读讲解

字符串长度、容量与结束符

char s[6] = "hello"; 存储 h、e、l、l、o、空字符,共占 6 个位置。

<cstring> 中的 strlen 计算终止符前的长度,不包含终止符;strcmp 按字典顺序比较,返回负数、零或正数;strcpy 复制,strcat 追加,后两者要求目标空间足够。

sizeof(s) 对本地数组得到总字节数,而 strlen(s) 是当前文本长度。数组传到函数后往往退化为指针,不能再用 sizeof 参数求原数组容量。

读入时给输入长度上限,或使用 cin.getline(s, 容量)。若数组没有终止符,字符串函数可能继续越界读取;现代 C++ 中 string 通常更方便。

计算长度与预留拼接空间

例1:长度和容量不同

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char s[10] = "cat";
    cout << strlen(s) << " " << sizeof(s) << endl;
    cout << (strcmp(s, "cat") == 0) << endl;
}

输出第一行 3 10,第二行 1。终止符不计入长度,但占用数组空间。

例2:为拼接预留空间

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char s[8] = "abc";
    const char tail[] = "de";
    if (strlen(s) + strlen(tail) + 1 <= sizeof(s)) strcat(s, tail);
    cout << s << endl;
}

输出 abcde。需要 3+2+1=6 个位置,容量 8 足够;额外的 1 是终止符。

提示

先修知识

技术参考

范围说明

本站讲解由 InfoCode 编写,不是官方考纲;参考级别是本站映射,不代表官方等级、认证或参赛资格。练习记录不等于掌握或资格。

参考级别:GESP 3 级(本站映射)

查看赛事关系与路径