Changing address contained by pointer using function

后端 未结 5 594
终归单人心
终归单人心 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:14

    In C, variables are passed by value - a copy of the pointer is passed to the function. Use another pointer to the pointer instead:

    void change(int **p, int *someOtherAddress)
    {
        *p = someOtherAddress;
    }
    
    int a = 1, b = 2;
    int *p = &a;
    
    printf("*p = %d\n", *p);
    change(&p, &b);
    printf("*p = %d\n", *p);
    

    This prints

    *p = 1
    *p = 2
    

提交回复
热议问题