> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/strings/char-array-length.md).

# 字符数组的有效长度

### 字符数组与字符串的区别

* **字符数组** `char s[N]`：以 `'\0'` 结尾，长度固定。
* **string**：C++ 标准库类型，自动管理长度，更安全。

求长度要用对方法：

| 对象      | 方法                         |
| ------- | -------------------------- |
| string  | `s.size()` 或 `s.length()`  |
| char 数组 | `strlen(s)`（需 `<cstring>`） |

> ⚠️ 常见错误：对字符数组用 `size()`（字符数组没有成员函数 size()）。`size()` 只能用于 string。

### strlen 的原理

`strlen` 从首地址开始数，直到遇到 `'\0'` 才停止，所以字符数组**必须有结尾的 \0**。

```cpp
#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char s[20] = "hello";       // 实际内容 h e l l o \0
    cout << strlen(s) << endl;  // 5，不含 '\0'
    cout << sizeof(s) << endl;  // 20，数组总字节数（注意区别！）
    return 0;
}
```

### 手写求长度

```cpp
int len = 0;
while (s[len] != '\0') len++;
```

### 输入与长度

```cpp
char s[100];
cin >> s;              // 遇空格/换行停止，读入一个单词
cin.getline(s, 100);   // 读入一整行（含空格）
cout << strlen(s);
```

### 要点

* `sizeof(s)` 是数组占用的字节数，不是有效字符数。
* 字符数组必须预留 `'\0'` 的位置：存 n 个字符至少开 `n+1`。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/strings/char-array-length.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
