You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

指针(Pointers)与*运算符技术问询:示例中*运算符的工作原理

关于C语言中*运算符的工作原理详解

Hey there! Let's break down exactly how the * operator works in your example, and why *p = 0 ends up setting the variable x to 0. I'll use a typical code snippet matching your疑惑点 to make this concrete:

int x = 10;    // 普通int变量,存储在某个内存地址中
int *p;        // 声明指针变量p,这里的*用来标记变量类型
p = &x;        // 把x的内存地址赋值给指针p
*p = 0;        // 核心疑惑:为什么这行能改变x的值?

1. *运算符的两个完全不同的角色

First, it's critical to distinguish the two jobs * does in C—they look the same but serve totally different purposes:

  • 角色1:声明指针时的类型标记
    When you write int *p;, the * isn't an operational operator here. It's just telling the compiler: "p isn't a regular int variable. It's a pointer variable, designed to store the memory address of an int-type variable." You can think of it as shorthand for "p is a pointer to an int".

  • 角色2:运行时的解引用(Dereference)操作
    When you write *p = 0;, this * is a functional operator. Its job is to "follow the address stored in the pointer, locate the corresponding memory slot, and access the value stored there". This action is called "dereferencing" the pointer.

2. 为什么*p = 0会修改x的值?

Let's walk through the process step by step:

  1. int x = 10;:The program allocates a chunk of memory for x—say its address is 0x7ffeefbff5ac (actual addresses are assigned by the system). The value 10 is stored in this address.
  2. p = &x;:The & is the "address-of" operator, which returns the memory address of x. This line assigns that address (0x7ffeefbff5ac) to pointer p, so now p holds the exact location of x in memory.
  3. *p = 0;:Here, the * dereferences p—it means "go to the address stored in p (which is x's address) and change the value there to 0". Since we're directly modifying the memory slot where x lives, x's value becomes 0 as a result.

一个通俗的类比

Think of it like this:

  • Variable x is a storage box in your house, holding 10 apples.
  • Pointer p is a piece of paper with your home's address written on it.
  • &x is writing your home address onto that paper.
  • *p is taking that paper, finding your house, and opening the storage box.
  • *p = 0 is replacing the 10 apples in the box with 0 apples—so the box (x) now has 0 apples.

关键总结

  • 声明时的*:仅用于标记变量为指针类型,不执行任何操作。
  • 运行时的*:解引用指针,直接访问指针指向的内存地址中的值。
  • *p is functionally equivalent to the variable p points to—so assigning to *p is the same as assigning to that variable.

内容的提问来源于stack exchange,提问作者AMayer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:17:13