存储字符指针,然后稍后填充

Storing char pointers then fill it later on

本文关键字:填充 然后 字符 指针 存储      更新时间:2023-10-16

我在这里遇到了一个小问题,所以我将一个char指针(而不是一个数组)存储在一个void指针中,如下所示:

char result[255];
CEVariable result_var(CEType::string, result);

现在,result_var被传递到我的引擎,存储为指针,然后稍后访问变量结构:(m_pData是一个void*,指向char数组)

strcpy((char*)pVar->m_pData, "42");

但没有数据写入其中,而且我确信它指向结果数组,因为我检查了地址。也许我对空指针的理解有点错误,但以下内容似乎有效:(只是测试)

    char dest[255];
    void*ptr = dest;
    strcpy((char*)ptr, "asdsa");
    std::cout << dest;

结果数组变成不可读的格式,很可能是随机内存。也许从来没有写信给我。我的问题是可能是什么问题?

编辑:CE变量::

class CEVariable
{
public:
    CEVariable() {}
    CEVariable(CEType t, void* mem)
    {
        m_Type = t;
        m_pData = mem;
    }
    // Variable Type
    CEType m_Type;
    // Variable Data Ptr
    void* m_pData;
};

结果不会超出范围,因为所有操作都在一个函数中执行。

谢谢你抽出时间。

如果具有char result[255]的作用域不再"活动",则这是未定义的行为。您需要使用new来分配堆内存,或者使其成为static

您的CEVariable::m_pData只是指针。它没有为字符串保留空间。

您应该首先为字符串分配一些内存(例如,使用new[]),然后将源字符串strcpy()分配给该保留空间:

// Dynamically allocate some memory with new[].
// For the string "42", it's 3 chars: '4', '2' and terminating NUL ''.
// For a generic string, you may want to use strlen(s)+1.
pVar->m_pData = new char[3];
// Copy string
strcpy(static_cast<char*>(pVar->m_pData), "42");
// Don't forget to release the string memory with delete[]
// when it's no longer needed.
// (e.g. in CEVariable's destructor.)

请注意,在C++中,应该使用C++样式的强制转换,而不是C样式的强制类型转换。

堆栈分配缓冲区char result[255]的问题是,当变量超出范围时,它将被销毁。相反,如果使用new[](来自)分配字符串内存,则在作用域结束大括号}之后,该内存仍然可用。当您在指针上调用delete[]时,内存将被释放。

在这段代码中:

char result[255];
CEVariable result_var(CEType::string, result);

如果变量result是某个函数中的局部变量,则需要确保在此函数的作用域之外时不要使用变量result_var