It’s common to pass a pointer to a function. Within the function, you can manipulate the data the pointer references without having to return that data from the function. This aspect of a pointer is what makes C a powerful — and scary — programming language. But what about when you need to manipulate the pointer’s address in the function?
While you can manipulate the data a pointer references, within a function you cannot manipulate the pointer itself (its address). That’s because the function doesn’t “own” the pointer variable; it uses a copy. Like any other variable passed to a function, the original variable is unchanged unless it’s a global (external) variable.
Pointers are confusing enough without having to add another layer of complexity, but occasionally I run into these types of puzzles. You will, too, unless you forget how variables are passed to functions and your brilliant program doesn’t work.
As is usually the case, it’s best to show sample code to illustrate the problem:
#include <stdio.h> void fourchar(char *p) { int x; for(x=0;x<4;x++) { putchar(*p); p++; } } int main() { char *text = "ABCD\n"; fourchar(text); putchar(*text); return(0); }
String text
is declared as a pointer in the main() function. Its address (text
) is passed to function fourchar(), which manipulates the pointer to display four characters in the string. In the function, each character is referenced by *p
and pointer p
is incremented.
When fourchar() returns, the putchar() function displays the character *text
. You might think that because p
was incremented in the fourchar() function, that the value of text
was also manipulated. If so, *text
references the '\n'
character in the string. But it doesn’t, as the program’s sample output shows:
ABCDA
The problem isn’t that the pointer is called p
in function fourchar() and text
in main(); they are two different variables. No, the problem is that only the pointer’s address is passed to the function; the pointer variable itself remains intact and unchanged inside the main() function. This aspect holds true for all variables passed to functions, but it’s extra weird because you can still manipulate a pointer’s referenced data.
Bottom line: When the fourchar() function returns, the putchar() statement displays the 'A'
in string text
. That’s because the address in text
hasn’t been changed within the main() function.
Still, after all this explaining and understanding, I have a question: How can the code manipulate a pointer within a function and have that manipulation stick?
For example, I want the fourchar() function to adjust the value of the text
pointer and have that manipulation retained when the function call returns. Such a thing is possible, and I’ll explore that solution in next week’s Lesson.