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'
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe