C 语言指针
创建指针
从上一章中我们了解到,我们可以通过引用运算符获得变量的 内存地址 &:
实例
#include <stdio.h>int main() {int myAge = 43;printf("%d\n", myAge);printf("%p\n", &myAge);return 0;}
在上面的例子中,&myAge 也被称为 指针。
指针 是存储另一个变量的内存地址作为其值的变量。
指针变量 指向同一类型的数据类型(如 int),并使用 * 运算符创建。正在使用的变量的地址被分配给指针:
实例
#include <stdio.h>int main() {int myAge = 43; // An int variableint* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge// Output the value of myAge (43)printf("%d\n", myAge);// Output the memory address of myAge (0x7ffe5367e044)printf("%p\n", &myAge);// Output the memory address of myAge with the pointer (0x7ffe5367e044)printf("%p\n", ptr);return 0;}
实例解释
创建一个名为 ptr 的指针变量,它 指向 一个 int 变量(myAge)。请注意,指针的类型必须与正在使用的变量的类型相匹配。
使用 & 运算符存储 myAge 变量的内存地址,并将其分配给指针。
现在,ptr 保存 myAge 的内存地址值。
不同之处
在上面的实例中,我们使用指针变量获取变量的内存地址(与&引用操作符一起使用)。
但是,您也可以使用*运算符(解引用算符)获取指针指向的变量的值:
实例
#include <stdio.h>int main() {int myAge = 43; // Variable declarationint* ptr = &myAge; // Pointer declaration// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)printf("%p\n", ptr);// Dereference: Output the value of myAge with the pointer (43)printf("%d\n", *ptr);return 0;}
请注意,* 符号在这里可能会令人困惑,因为它在我们的代码中做了两件不同的事情:
- 在声明(int* ptr)中使用时,它会创建一个指针变量。
- 当不是在声明时,它充当解引用运算符。
我为什么要学习指针? 指针在 C 语言中很重要,因为它能让你操作计算机内存中的数据——这可以减少代码并提高性能。
提示:有三种方法可以声明指针变量,但第一种方法最常用:
int* myNum; // 最常使用int *myNum;int * myNum;