Click to See Complete Forum and Search --> : pointers passed by reference or by value?
f'lar
12-10-2001, 01:38 PM
I have a friend taking a web developement class, and he was having some problems with a cgi program he was writing. He had to parse a string, and used a pointer that he moved around inside the string. He had a function that accepted the pointer as a parameter, and then would modify the pointer. He wanted the changes to stick, ie for the pointer to be passed by reference, but I don't know that it is by default, and the syntax for how to do that is confusing:
void function (char *& pointer)
{
}
The ampersand means different things when used next to a pointer, so what will happen here?
EscapeCharacter
12-10-2001, 03:21 PM
the proper way would be
void function(char *string){
*string = "newstring";
}
*string tells the compiler to put "newstring" into the actual memory location of string not the pointers memory
miller
12-10-2001, 03:29 PM
Your function needs to take a pointer to a pointer.
void function(char **p) {
}
Strogian
12-10-2001, 04:59 PM
Yeah, the answer is clear in C: use a pointer to a pointer. But then C++ came along and screwed everything up with it's bizarre referencing system. (I don't know C++, btw.) :D
Stuka
12-10-2001, 05:09 PM
Strogian - referencing isn't bizarre at all. All it does is syntactically sugar coat using the & operator to pass a pointer to a variable. As you said, in C, your function would accept a pointer to whatever you wanted to be passed by reference. In C++, you use the & after the variable type in the parameter list to do the same thing, which means that USERS of your function just hand over a variable name, rather than using the & operator themselves. Same process, different look.
eflashj
12-19-2001, 04:59 PM
Anything you know how to do in C can be done the same way in C++ as long as you make the proper #includes (i.e preprocessor directives to include header files). Write your code exactly as you would in C and don't get hung up on the ++. Trust me, it will work. C++ has a lot of cool advantages over C, but they're mostly for OOP. Even then, the methods of an OOP program can be written exactly like structured functions in C because that's all they really are.