存储字符指针,然后稍后填充
Storing char pointers then fill it later on
我在这里遇到了一个小问题,所以我将一个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
。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 在c++中用vector填充一个简单的动态数组
- 如何使用用户输入在C++中正确填充2D数组
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 如何找到大小'x'数组是否完全填充,在C++?
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- boost::asio如何生成多个协同程序,然后加入它们
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 在std::thread中,joinable()然后join()线程安全吗
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- QT-仅用密钥填充QMAP,然后添加每个键的值
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- C - 分配一个未签名的炭缓冲区,然后用字符串填充
- 用点填充一条线,然后寻找与轮廓的交叉点
- 声明一个表,然后填充一个表
- 如何用自己的值填充tm结构,然后打印出来
- 更快的方式,然后我填充一个唯一的整数除了两个值的向量?c++
- 存储字符指针,然后稍后填充