我如何将其转换为返回char *而不是使用std :: string 只想在没有std :: string
的情况下学习其他方法string getName(DWORD Address)
{
DWORD BaseDword = ReadBaseDword(Address);
int size = ReadCharSize();
string name = "";
for (int i = 0; i < size - 1; i++)
{
char c = ReadCharArrayChar(i);
name += c;
}
return name;
}
答案 0 :(得分:4)
其他方式很难看,这是std::string
存在的原因之一:)。但出于教育目的,以下是您如何返回char*
(如提出的那样):
// caller is responsible for deleting the return value
char* getEntityName(DWORD Address)
{
DWORD BaseDword = ReadBaseDword(Address); // (not sure what this achieves)
int size = ReadCharSize();
char* name = new char[size];
name[size - 1] = '\0';
for (int i = 0; i < size - 1; i++)
{
char c = ReadCharArrayChar[i](); // odd looking, but I'll assume this works
name[i] = c;
}
return name;
}
类似的选项仍然使用缓冲区的原始指针,但让调用者传入它(及其大小):
// returns: true iff the buffer was successfully populated with the name
// exceptions might be a better choice, but let's keep things simple here
bool getEntityName(DWORD Address, char* buffer, int maxSize)
{
DWORD BaseDword = ReadBaseDword(Address); // (not sure what this achieves?)
int size = ReadCharSize();
if(size > maxSize)
return false;
buffer[size - 1] = '\0';
for (int i = 0; i < size - 1; i++)
{
char c = ReadCharArrayChar[i](); // odd looking, but I'll assume this works
buffer[i] = c;
}
return true;
}
后一种选择允许,例如:
char buffer[100];
getEntityName(getAddress(), buffer, 100);
答案 1 :(得分:2)
char * getEntityName(DWORD Address)
{
DWORD BaseDword = ReadBaseDword(Address);
int size = ReadCharSize();
char* name = malloc (size);
for (int i = 0; i < size - 1; i++)
{
name[i] = ReadCharArrayChar[i]();
}
name[size - 1] = 0;
return name;
}
请注意,调用者在完成后应该free
返回值。这假定size
包括终止零字节,它似乎给出了示例代码。
答案 2 :(得分:1)
如果我绝对无法使用std::string
,我会使用std::vector<char>
:
std::vector<char> getName(DWORD Address)
{
DWORD BaseDword = ReadBaseDword(Address);
const int size = ReadCharSize();
std::vector<char> name(size);
for (int i = 0; i < size - 1; i++)
{
name[i] = ReadCharArrayChar(i);
}
name[size - 1] = '\0';
return name;
}
或std::unique_ptr<char[]>
如果我知道调用者永远不需要修改结果:
std::unique_ptr<char[]> getName(DWORD Address)
{
DWORD BaseDword = ReadBaseDword(Address);
const int size = ReadCharSize();
std::unique_ptr<char[]> name(new char[size]);
for (int i = 0; i < size - 1; i++)
{
name[i] = ReadCharArrayChar(i);
}
name[size - 1] = '\0';
return name;
}