> 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/basics/pointers.md).

# 指针

### 指针是什么

指针是一个**存放地址**的变量。普通变量存数据，指针变量存“某数据在哪”。

```cpp
int a = 10;
int *p = &a;   // p 存放 a 的地址
cout << *p;    // 10，* 解引用，访问 p 指向的变量
*p = 20;       // 通过指针修改 a
```

### 两个核心运算符

* `&` 取地址：`&a` 得到变量 a 的地址
* `*` 解引用：`*p` 访问 p 指向的值

### 指针与数组

数组名本质上是首元素地址，`a[i]` 等价于 `*(a + i)`。

```cpp
int a[3] = {10, 20, 30};
int *p = a;
cout << *p << endl;       // 10
cout << *(p + 2) << endl; // 30
cout << p[1] << endl;     // 20
```

### 指针的算术

`p + 1` 不是加 1 字节，而是跳到**下一个同类型元素**，移动 `sizeof(类型)` 字节。

### 空指针

```cpp
int *p = nullptr;   // 不指向任何地址
if (p == nullptr) cout << "空指针";
```

### 指针与结构体

用 `->` 通过结构体指针访问成员：

```cpp
struct Node { int a; string s; };
Node n{5, "hi"};
Node *p = &n;
cout << p->a << " " << p->s;   // 5 hi
```

### 常见用途

* 函数参数传递（指针传递，可修改实参）
* 动态内存分配（`new` / `delete`）
* 构建链表、树等动态数据结构

> 陷阱：野指针（未初始化的指针）解引用会崩溃；指针指向的数组越界是未定义行为。


---

# 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/basics/pointers.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.
