Changing the Value of Pointers Passed as Arguments
Understand how to change the value of pointers passed as arguments to functions in C. This lesson explains why a pointer itself does not change when passed by value and how to use pointers to pointers to modify the original pointer. You will explore examples and best practices for safely managing pointer references.
Introduction
Our goal is to change the value of a pointer passed as an argument to a function. To be clear, we don’t want to change the variable that the pointers point to (with the dereference operator). We want to change the pointer itself and make it point somewhere else.
As a starting point, we’ll write a function called setToNULL, which receives an int pointer and sets it to NULL.
First attempt
Well, if we want to set a pointer to NULL, we usually do:
pointer = NULL;
Therefore, let’s try the same thing, but in a function. We’ll create a pointer, assign it a valid memory address, ...