very simple pass by reference question

M

michael

Hi All,

How do I pass a reference to a pointer and update the pointer in the
function? I have:

void goGetString(char *str){
string inString;

cin >> inString;
str = new char[inString.length()+1];
strcpy(str, inString.c_str());
cout << "String is " << str << endl;
}

int main(){
char *someStr;

goGetString(&*someStr);
cout << "String was " << someStr << endl;
}

why is someStr not changed ?

Thanks for your help

Michael
 
P

pmouse

1. send the pointer to the pointer to char (ptc), because it's the
ptc's value that you want to change

void goGetString(char **str)
{
...
*str = new char[ ... ];
strcpy ( *str, ... );
}


to call:
char* someStr;
goGetString( &someStr );

2. send the reference to the pointer to char (ptc)
void goGetString(char *& str)
{
...
str = new char[...]
strcpy( str, ... );
}

to call:
char* someStr
goGetString(someStr);
 
T

Tor Einar =?UTF-8?B?VMO4bm5lc3Nlbg==?=

You also have an issue concerning memory-management in your code. See if you
can see what that issue is.

tet
 
L

Lionel B

Hi All,

How do I pass a reference to a pointer and update the pointer in the
function? I have:

#include <iostream>
#include <string>

using namespace std;
void goGetString(char *str){

void goGetString(char*& str){ // takes _reference_ to pointer
string inString;

cin >> inString;
str = new char[inString.length()+1];
strcpy(str, inString.c_str());
cout << "String is " << str << endl;
}

int main(){
char *someStr;

goGetString(&*someStr); // ??? This is just someStr

goGetString(someStr);
cout << "String was " << someStr << endl;

delete [] someStr; // prevent memory leak
}

why is someStr not changed ?

It wasn't changed because you passed the pointer in to goGetString() by
_value_.

BTW, why not let goGetString take a string& as parameter, rather than
using char* ?

#include <iostream>
#include <string>

using namespace std;

void goGetString(string& str)
{
cin >> str;
cout << "String is " << str << endl;
}

int main()
{
string someStr;

goGetString(someStr);
cout << "String was " << someStr << endl;
}

Much simpler and less error-prone.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top