Changing address contained by pointer using function

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.

Leave a Comment