c++ - 读取字符到(字符指针)

标签 c++ c

我如何将其转换为返回 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/

相关文章:

c++ - 如何使用样式表设置QToolButton 的图标?

c++ - adjustROI 会改变 cv::Mat 的 wholeSize 吗?

c# - 无法更改 VS 2015 C++ 项目中的 .NET 目标框架版本

c - 是什么导致我的程序挂起并且无法正常退出? (管道,读取系统调用,while 循环)

c++ - argc从哪里来?

c - 如何修复构建 Linux 内核时出现的链接错误?

c - 使用 longjmp 在 Lua 中处理错误

c - 简单的二维

c - 没有线程或高级库的 C 并行编程

c++ - 查找可以从 CMD 运行的可执行文件的绝对路径