我如何将其转换为返回 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;
}
最佳答案
其他方式很丑陋,这是 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);
关于c++ - 读取字符到(字符指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24002193/