Mail Archives: djgpp/1999/03/13/16:10:52
In article <3 DOT 0 DOT 6 DOT 16 DOT 19990313015041 DOT 1dbffe6a AT pop DOT detroit DOT crosswinds DOT net>,
djgpp AT delorie DOT com wrote:
>I have never quite figured out how to pass a pointer to a function and have
>the function update the variable sent to it. So, for many years I have
>just found ways to work around this little glitch in my memory. Now, I
>have come to a point in a program that I'm writing where I can't work
>around the problem anymore.
[snip]
>So, how would I go about doing this? That is, how would I call the
>function and how would I perform the update?
Just passing a pointer to a function [void function(char *input)] gives
the address the pointer points to, it doesn't tell the function where the
pointer itself is, so it doesn't know how to change it.
If you want to have a function update not just the data a pointer points
to, but the address it points to, you need to pass the address of the
pointer. That address points to the pointer. Here's a short program
demonstrating this.
#include <stdio.h>
void change_pointer(char **in) /*This means it expects a pointer to a char
pointer.*/
{
*in+=6; /*update the pointer that in points to.*/
return;
}
main()
{
char text[]="Don't Edit Me!\n";
char *text_pointer;
text_pointer=text;
printf("%s",text_pointer); /*before....*/
change_pointer(&text_pointer); /*That means, pass the address of the
pointer, NOT the address of the text*/
printf("%s",text_pointer); /*After*/
return(0);
}
Output;
Don't Edit Me!
Edit Me!
The actual text isn't changed, text_pointer just points to a different
part of the text.
Does this answer your question?
- Raw text -