Talk about the pointer as an argument and changing its value

  • 2020-04-02 01:48:37
  • OfStack


#include<stdio.h> 
int f(int *p){ 
    p = p+1; 
    return printf("%dn",*p); 
} 
void main(){ 
    int a[]={1,2}; 
    int *p = a;//Pointer p is the first address
    f(p);//call
    printf("%d",*p);//The value of p is not going to change
}

Results:
2
1
Press any key to continue


#include<stdio.h> 
void z(int *p){ 
    p = p+1; 
    *p = 100; 
} 
void mian(){ 
    int a[] = {1,2}; 
    int *p = a; 
    z(p);//call
    printf("a[1]=%d",*(p+1));//The value in the memory space pointed to by the pointer (p+1) has changed
}

Results:
A [1] = 100
Press any key to continue

  From the above and below examples, it can be concluded that when a pointer is passed as an argument, the value (the address to which the pointer points) cannot be changed in other functions, but the pointer can be changed
The value in the address pointed to.
  Therefore, to achieve the value exchange between two first-level Pointers, we need to use the second-level pointer to achieve :(pointer q to a, pointer p to b, q to b, p to a).


#include<stdio.h> 
void exchange(int **x,int **y){ 
    int *temp; 
    temp = *x;//*x=*qq=&a 
    *x = *y; 
    *y = temp; 
} 

void main(){ 
    int a =100; 
    int b = 12; 
//Define a pointer
    int *q = &a; 
    int *p = &b; 
    int **qq = &q; 
    int **pp = &p; 
//The output
    printf("q=%pn",q); 
    printf("p=%pn",p); 
    //Call the function to perform the transformation
    exchange(qq,pp); 

    printf("======== altered ==========n"); 
    printf("q=%pn",q); 
    printf("p=%pn",p); 
}

Results:
Q = 0012 ff44
P = 0012 ff40
======== === changed ======== =======
Q = 0012 ff40
P = 0012 ff44
Press any key to continue


Related articles: