Changing address contained by pointer using function

后端 未结 5 676
终归单人心
终归单人心 2020-11-21 06:49

If I\'ve declared a pointer p as int *p; in main module, I can change the address contained by p by assigning p=&a; w

5条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 07:18

    If you want to alter the content of a variable in a function in C, pointer is a kinda variable as well, you have to pass it by pointer or indirect reference by using always & address and * dereference operators. I mean * operator is always used and preceded when changing the value of a variable.

    #include 
    #include 
    
    
    void changeIntVal(int *x) {
        *x = 5;
    }
    
    void changePointerAddr(int **q) {
        int *newad;
        *q = newad;
    }
    
    void changePPAddr(int ***q) {
        int **dummy;
        *q = dummy;
    }
    
    int main() {
        int *p;
        int **pp;
        int *tempForPP;
        int a = 0;
        printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);
    
    
        p = &a;
        pp = &tempForPP;
        printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);
    
        changeIntVal(&a);        // ----
                                 //    |---
        changePointerAddr(&p);   // ----  |---->  parts of what I mean
                                 //    |---
        changePPAddr(&pp);       // ----
    
        printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);
    
        return 0;
    
    }
    

提交回复
热议问题