[C++] char[] to string conversion

07/22/2010 13:32 AutoItDude#1
hi,

I have a problem with conversion char to string.

Code:
char GetUnitName()
{
	char cUnitName[16];
	memcpy(cUnitName,(void*)0x007E7A38,16);

	return cUnitName[strlen(cUnitName)];
}

string UnitName = GetUnitName();
printf("UnitName=%s\n",UnitName);
this doesn't work. I tried
Code:
char UnitName[] = GetUnitName();
string strUnitName(UnitName);
but this does not work to me as well so my question is:
how to convert char array into string properly?
07/22/2010 13:44 ms​#2
Code:
char *GetUnitName()
{
	char *pUnitName = new char[16];
	memcpy(pUnitName,(void*)0x007E7A38,16);

	return pUnitName;
}
Either
Code:
char *pUnitName = GetUnitName();
string UnitName = pUnitName;
delete pUnitName;
printf("UnitName=%s\n", UnitName.c_str());
or simply

Code:
char *pUnitName = GetUnitName();
printf("UnitName=%s\n", pUnitName);
delete pUnitName;
07/23/2010 14:59 xNopex#3
Long time ago I read an article which explained that it is not a good idea to receive a pointer from a function as the return value. According to the article you should pass the pointer as a parameter to the function instead. For example:

Code:
void GetString( std::string* pStr )
{
    char cUnitName[16];
    memcpy( pUnitName,(void*)0x007E7A38, 16 );
    std::string asString = cUnitName;
    *pStr = asString;
}

I didn't test this code but I think it should work. I do not think that the article was right that you mustn't receive pointers as return values. I think everyone should decide for himself or herself which way he or she prefers.