Deep dive into pointers and memory operations in C深入理解 C 语言指针概念与内存操作
What is a Pointer?什么是指针?
A pointer stores a memory address rather than a value. With pointers, you can manipulate memory directly to implement efficient memory management and complex data structures.指针存储的是内存地址而不是直接的值。通过指针,我们可以直接操作内存,实现高效的内存管理与复杂的数据结构。
内存可视化:
内存地址 0x1000: 10 (变量 int a = 10)
内存地址 0x1004: 0x1000 (指针 int *ptr = &a)
指针ptr存储的是变量a的内存地址
int a = 10; // 普通变量int *ptr = &a; // 指针变量,存储a的地址int value = *ptr; // 解引用,获取地址上的值
Core Pointer Operations指针的核心操作
1. 声明指针
int *ptr1; // 指向整数的指针char *ptr2; // 指向字符的指针float *ptr3; // 指向浮点数的指针
2. 获取地址 (&)
int x = 42;
int *ptr = &x; // &x 获取变量x的内存地址
3. 解引用 (*)
int x = 42;
int *ptr = &x;
printf("%d\n", *ptr); // 输出: 42
*ptr = 100; // 修改x的值为100
💡 记忆技巧
&: address-of operator&: 取地址运算符
*: dereference operator*: 解引用运算符
ptr: the pointer itself (stores an address)ptr: 指针本身(存储地址)
*ptr: the value pointed to*ptr: 指针指向的值
Pointers as Function Parameters指针作为函数参数
Passing pointers enables call-by-reference semantics so functions can modify the caller’s variables.通过指针作为函数参数,我们可以实现引用传递,让函数能够修改调用者的变量。
// 错误的方式:值传递,无法修改原变量voidswap_wrong(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// 正确的方式:指针传递,可以修改原变量voidswap_correct(int *a, int *b) {
int temp = *a; // 解引用获取值
*a = *b; // 修改a指向的值
*b = temp; // 修改b指向的值
}
🎯 RGB Color Rotation ExampleRGB颜色转换实例
Let’s implement an RGB color rotation function — a classic Week 1 exercise:让我们实现一个RGB颜色轮换函数,这是Week 1的经典练习:
voidchange_colour(int *red, int *green, int *blue) {
int temp = *red; // 保存red的值
*red = *blue; // new red = old blue
*blue = *green; // new blue = old green
*green = temp; // new green = old red
}
Pointers and Arrays指针与数组
An array name is effectively a pointer to its first element.数组名本质上就是指向数组第一个元素的指针。