C language notes 15 - secondary pointer

secondary pointer stores the address of the first-level pointer, the secondary pointer can modify the content pointed to by the first-level pointer, the two are like the relationship between the upper and lower levels. There are many changes to the pointer, which have a huge effect on arrays and functions. The biggest feature of the second-level pointer is that there are two **, define a second-level pointer: int **p; 1. The value of the second pointer changes the variable

#include<stdio.h>
#include<stdlib.h>
void main()
{
    int a=10;
    int *p=&a;
    int **pp=&p;//The second pointer has two **
    printf("a=%d\n",a);
    **pp=20;// The second pointer directly modifies the value pointed to by the first pointer printf("a=%d\n",a);
    printf("a=%d\n",*p);
    system("pause");
}

这里写图片描述 由结果可以知道,即使一级指针p没有进行修改变量的值,只要二级指针修改了,变量的值也会发生改变。 2.改变一级指针指向的地址

#include<stdio.h>
#include<stdlib.h>
void main()
{
    int a=10;
    int b=20;
    int *p=&a;
    int **pp=&p;// Secondary pointers have two **
    printf("*p=%d\n",*p);
    *pp=&b;// Modify the address pointed to by the first level printf("*p=%d\n",*p);
    system("pause");
}

这里写图片描述 二级指针改变了一级指针指向的地址。 3.二级指针遍历指针数组

#include<stdio.h>
#include<stdlib.h>
void main()
{
    char *a[] = { "lwj", "jib", "hehe", "jiuzhe", "ffff" };
    int len=(sizeof(a)/sizeof(char *));// Find the array length 
    for(char **p=a;p<a+len;p++)//a as a pointer, need secondary pointer traversal || |{
    {
        printf("%s\n",p);
    }
    system("pause");
}

这里写图片描述 4.二级函数指针改变一级函数指针 函数定义:int add(); 函数指针定义:int (*p)();//把函数名去掉,再把指针名填上。 下面写一个用二级函数指针改变一级函数指针指向的函数。开始一级函数指针先指向加函数,用二级函数指针让一级函数指针指向减函数。

#include<stdio.h>
#include<stdlib.h>
int add(int a,intb)//Add function
{return a+b;
}
int sub(int a, int b)//minus function
{
    returna-b;
}
/ / Change the function pointed to by the function pointer
Void change_fun(int (**pp)(int,int))
{
    *pp=sub;//*pp is the function address pointed to by the first-level function pointer
}
Void main()
{int a=20,b=10;
    int(*p)(int,int)=add;//The function name is the address of the function printf("result=%d\n",p(a,b));//call the function pointed to by p
    Change_fun(&p);// The address of the incoming function pointer printf("result=%d\n",p(a,b));//call the function pointed to by psystem("pause");
}

这里写图片描述 使用指针最大的麻烦是指针的类型,类型不一致就会出先各种错误。当指针的级数越来越多,就会变得难以理解。