Modifying a pointer inside a function
What you'll learn: How to use a pointer-to-a-pointer to update a memory address across function boundaries.
The "Postcard" Analogy
Think of a regular pointer as a postcard with an address written on it. If you pass that postcard to a function, C makes a photocopy of it. The function can follow the address to change what’s inside the house (the data), but if the function writes a new address on its copy of the postcard, your original postcard back in main() stays the same.
To let a function change the address on your original postcard, you must give the function a pointer to the postcard itself. This is a pointer-to-a-pointer.
Why we need them
Normally, if you pass a pointer to a function and try to redirect it (like allocating new memory or moving to the next node in a list), the change is lost when the function ends. By using a double pointer (**), you give the function the "remote control" to the original pointer variable.
The code in action
In this example, we want a function to point our local pointer to a specific string.
#include <stdio.h>
// We use char** because we want to change a char*
void updateMessage(char **ptrToPtr) {
static char *secretMessage = "Hello from the new address!";
// We dereference once to reach the original pointer,
// then change where it points.
*ptrToPtr = secretMessage;
}
int main() {
// 1. Start with a pointer pointing to nothing (NULL)
char *myMessage = NULL;
// 2. Pass the ADDRESS of the pointer (&)
updateMessage(&myMessage);
// 3. Now myMessage has been updated!
printf("%s\n", myMessage);
return 0;
}
How it works
- The Setup:
char *myMessageis a box that holds a memory address. - The Hand-off: When we call
updateMessage(&myMessage), we aren't passing the NULL value; we are passing the location of the box itself. - The Modification: Inside the function,
*ptrToPtrmeans "go to the box located at this address." The assignment*ptrToPtr = secretMessageputs a new address inside that box.
Without that extra level of indirection (the second *), the function would only be changing a local copy, leaving your original pointer pointing at nothing.
Key takeaway
To change where a pointer points from inside a function, you must pass the address of that pointer (&ptr) and receive it as a double pointer (**ptr).