I’m a newbie to C++. I’m trying to have a char pointer as an out parameter for a function. But the changes made in the function are not reflected in the main function. What am I doing wrong?
void SetName( char *pszStr )
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
pszStr = pTemp;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* pszName = NULL;
SetName( pszName );
cout<<"Name - "<<*pszName<<endl;
delete pszName;
return 0;
}
Your pointer is being copied onto the stack, and you’re assigning the stack pointer. You need to pass a pointer-to-pointer if you want to change the pointer:
That will solve your problem.
However, there are other problems here. Firstly, you are dereferencing your pointer before you print. This is incorrect, your pointer is a pointer to an array of characters, so you want to print out the entire array:
What you have now will just print the first character. Also, you need to use
delete []to delete an array:Bigger problems, though, are in your design.
That code is C, not C++, and even then it’s not standard. Firstly, the function you’re looking for is
main:Secondly, you should use references instead of pointers:
Aside from that, it’s usually better to just return things if you can:
There is something that makes this all better. C++ has a string class:
If course this can all be simplified, if you want:
You should work on your formatting to make things more readable. Spaces inbetween your operators helps:
Just like spaces in between English words helps, sodoesspacesbetweenyouroperators. 🙂