What is the method for assigning values to a C language double pointer?

In C language, a double pointer refers to a pointer that points to another pointer. To assign a value to a double pointer, first define a single pointer that points to a variable, and then define a double pointer that points to this single pointer. Finally, assign a value to the single pointer through the double pointer.

Below is an example code:

#include <stdio.h>

int main() {
    int num = 10;
    int *ptr = &num; // 定义一级指针指向num变量
    int **pptr = &ptr; // 定义二级指针指向ptr指针

    printf("num = %d\n", num);
    printf("*ptr = %d\n", *ptr);
    printf("**pptr = %d\n", **pptr);

    // 给二级指针赋值
    int newNum = 20;
    *ptr = newNum;

    printf("num = %d\n", num);
    printf("*ptr = %d\n", *ptr);
    printf("**pptr = %d\n", **pptr);

    return 0;
}

In the example above, we first defined a variable num, then defined a first-level pointer ptr pointing to the num variable. Next, we defined a second-level pointer pptr pointing to the ptr pointer. By assigning a value to ptr using the second-level pointer pptr, we indirectly modified the value of num.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds