C 语言中的双指针**
本篇文章介绍如何使用指向指针的指针(双指针或**)来存储另一个指针变量的地址。
C 语言中变量的内存分配
在创建变量时,将分配一些特定的内存块给该变量用于存储值。例如,我们创建了一个 char 变量 ch 和值 a。在内部,一个字节的内存将分配给变量 ch。

C 指针
在 C 编程中,指针是存储另一个变量地址的变量。要访问该地址中存在的值,我们使用*。

#include <stdio.h>
int main()
{
char ch = 'a'; // create a variable
char *ptr = &ch; // create a pointer to store the address of ch
printf("Address of ch: %p\n", &ch); // prints address
printf("Value of ch: %c\n", ch); // prints 'a'
printf("\nValue of ptr: %p\n", ptr); // prints the address of a
printf("*ptr(value of ch): %c\n", *ptr); // Prints Content of the value of the ptr
}
输出:
Address of ch: 0x7ffc2aa264ef
Value of ch: a
Value of ptr: 0x7ffc2aa264ef
*ptr(value of ch): a
在上面的代码中,
-
创建一个
char变量ch并将字符a分配为一个值。 -
创建一个
char指针ptr并存储变量ch的地址。 -
打印
ch的地址和值。 -
打印
ptr的值,ptr的值将是ch的地址 -
使用
*ptr打印ch的值。ptr的值是变量ch的地址,在该地址中存在值'a',因此将打印它。
C 语言中指向指针的指针(**)
为了存储变量的地址,我们使用指针。同样,要存储指针的地址,我们需要使用(指向指针的指针)。 表示存储另一个指针地址的指针。
要打印指向指针变量的指针中的值,我们需要使用**。

#include <stdio.h>
int main()
{
char ch = 'a'; // create a variable
char *ptr = &ch; // create a pointer to store the address of ch
char **ptrToPtr = &ptr; // create a pointer to store the address of ch
printf("Address of ch: %p\n", &ch); // prints address of ch
printf("Value of ch: %c\n", ch); // prints 'a'
printf("\nValue of ptr: %p\n", ptr); // prints the address of ch
printf("Address of ptr: %p\n", &ptr); // prints address
printf("\nValue of ptrToPtr: %p\n", ptrToPtr); // prints the address of ptr
printf("*ptrToPtr(Address of ch): %p\n", *ptrToPtr); // prints the address of ch
printf("**ptrToPtr(Value of ch): %c\n", **ptrToPtr); // prints ch
}
输出:
Address of ch: 0x7fffb48f95b7
Value of ch: a
Value of ptr: 0x7fffb48f95b7
Address of ptr: 0x7fffb48f95b8
Value of ptrToPtr: 0x7fffb48f95b8
*ptrToPtr(Address of ch): 0x7fffb48f95b7
**ptrToPtr(Value of ch): a
在上面的代码中,
-
创建一个
char变量ch并将字符a作为值分配给它。 -
创建一个
char指针ptr并存储变量ch的地址。 -
创建一个指向指针
ptrToPtr的char指针并存储变量ptr的地址。 -
ptr 将以变量
ch的地址作为值,而ptrToPtr将以指针ptr的地址作为值。 -
当我们像
*ptrToPtr那样取消引用ptrToPtr时,我们得到变量ch的地址 -
当我们像
**ptrToPtr那样取消引用ptrToPtr时,我们得到变量ch的值
要记住的要点
为了存储 ptrToPtr 的地址,我们需要创建
char ***ptrToPtrToPtr = &ptrToPtr;
printf("***ptrToPtrToPtr : %c\n", ***ptrToPtrToPtr); // 'a'
相关文章
在C中将整数转换为字符
发布时间:2024/01/03 浏览次数:131 分类:C语言
-
本教程介绍了在C中将整数转换为字符的不同方法。在C编程语言中,将整数转换为字符在各种情况下都很重要。在C中,字符是以ASCII值表示的,因此转换过程相对简单。
在 C 语言中使用 typedef enum
发布时间:2023/05/07 浏览次数:364 分类:C语言
-
本文介绍了如何在 C 语言中使用 typedef enum。使用 enum 在 C 语言中定义命名整数常量 enum 关键字定义了一种叫做枚举的特殊类型。
C 语言中的 extern 关键字
发布时间:2023/05/07 浏览次数:131 分类:C语言
-
本文介绍了如何在 C 语言中使用 extern 关键字。C 语言中使用 extern 关键字来声明一个在其他文件中定义的变量

