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:
void SetName( char **pszStr )
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
*pszStr = pTemp; // assign the address of the pointer to this char pointer
}
int _tmain(int argc, _TCHAR* argv[])
{
char* pszName = NULL;
SetName( &pszName ); // pass the address of this pointer so it can change
cout<<"Name - "<<*pszName<<endl;
delete pszName;
return 0;
}
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:
cout<<"Name - "<<pszName<<endl;
What you have now will just print the first character. Also, you need to use delete []
to delete an array:
delete [] pszName;
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
:
int main( int argc, char * argv[] )
Secondly, you should use references instead of pointers:
void SetName(char *& pszStr )
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
pszStr = pTemp; // this works because pxzStr *is* the pointer in main
}
int main( int argc, char * argv[] )
{
char* pszName = NULL;
SetName( pszName ); // pass the pointer into the function, using a reference
cout<<"Name - "<<pszName<<endl;
delete pszName;
return 0;
}
Aside from that, it's usually better to just return things if you can:
char *SetName(void)
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
return pTemp;
}
int main( int argc, char * argv[] )
{
char* pszName = NULL;
pszName = SetName(); // assign the pointer
cout<<"Name - "<<pszName<<endl;
delete pszName;
return 0;
}
There is something that makes this all better. C++ has a string class:
std::string SetName(void)
{
return "Mark";
}
int main( int argc, char * argv[] )
{
std::string name;
name = SetName(); // assign the pointer
cout<<"Name - "<< name<<endl;
// no need to manually delete
return 0;
}
If course this can all be simplified, if you want:
#include <iostream>
#include <string>
std::string get_name(void)
{
return "Mark";
}
int main(void)
{
std::cout << "Name - " << get_name() << std::endl;
}
You should work on your formatting to make things more readable. Spaces inbetween your operators helps:
cout<<"Name - "<<pszName<<endl;
cout << "Name - " << pszName << endl;
Just like spaces in between English words helps, sodoesspacesbetweenyouroperators. :)