# C 语言中的陷阱

## 函数中的内部变量会被回收

在 C 语言中，函数中的内部变量会在函数执行完成（调用出栈）之后被回收，因此不能将内部变量的指针赋值给函数外部的变量：

```c
void foo(char *p) {
  p = "Hello, World!";
  // 错误，函数中的内部变量会在函数执行完成（调用出栈）之后被回收
}
```

## `? :` 运算符优先级比 `+` `-` `*` `/` `%` 低

在 C 语言中，三目运算符 `? :` 的优先级是很低的，比 `+` `-` `*` `/` `%` 运算符都要低，因此需要注意避免出现以下问题：

```c
int i = 10 + ok ? 1 : -1;
// 该表达式的实际运算优先级是
// int i = (10 + ok) ? 1 : -1;
```

## 数组变量被当作指针处理

在 C 语言中，数组变量相当于该数组中第一个元素的地址，并且在调用函数过程中，被传递的数组变量实际上只是一个指针变量。因此例如 `sizeof nums / sizeof nums[0]` 之类的运算，应该在调用函数之前执行。

```c
void foo(int *nums) {
  int len = sizeof nums / sizeof nums[0];
  // 错误，nums 只是一个指针变量
}
```

## 结构体之间的类型转换

// TODO


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.fantasticmao.cn/tech/c-and-unix/c/c-yu-yan-zhong-de-xian-jing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
