Changing address contained by pointer using function

后端 未结 5 584
终归单人心
终归单人心 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 06:54

    In C, functions arguments are passed by value. Thus a copy is made of your argument and the change is made to that copy, not the actual pointer object that you are expecting to see modified. You will need to change your function to accept a pointer-to-pointer argument and make the change to the dereferenced argument if you want to do this. For example

     void foo(int** p) {
          *p = NULL;  /* set pointer to null */
     }
     void foo2(int* p) {
          p = NULL;  /* makes copy of p and copy is set to null*/
     }
    
     int main() {
         int* k;
         foo2(k);   /* k unchanged */
         foo(&k);   /* NOW k == NULL */
     }
    

    If you have the luxury of using C++ an alternative way would be to change the function to accept a reference to a pointer.

提交回复
热议问题