c++ - 为什么我的 char* 无故改变?

标签 c++ json qt

详细信息:

我正在使用这个 github 项目将 Json 转换为对象。

https://github.com/ereilin/qt-json

使用这个 json:

{
    "bin": "/home/pablo/milaoserver/compile/Devices01.olk",
    "temp":"/home/pablo/milaoserver/temporal/",
    "port": "1234",
    "name": "lekta",

}

用这两行我创建了两个字符指针:

 char* bin = configuration["bin"].toString().toLatin1().data();
 char* temp = configuration["temp"].toString().toLatin1().data();

调试应用我有正确的字符串。

但是当我使用它们时,具体的“bin”字符变为

`hom 

有什么想法吗?

评论中的解决方案:

问题是数据的“持久性”。

我找到了解决方案:

std::string binAux(configuration["bin"].toString().toLatin1().data());
std::string tempAux(configuration["temp"].toString().toLatin1().data());

char* bin = new char[binAux.size()+1] ;
strcpy(bin, binAux.c_str());

char* temp = new char[tempAux.size()+1] ;
strcpy(temp, tempAux.c_str());

最佳答案

这里的错误是因为临时对象。

toString() 创建一个分号后不再可用的临时对象。

标准状态:

12.2 Temporary objects [class.temporary]

3/ [...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.

也就是说,当您想访问它时,您有未定义的行为

这应该可以解决您的问题:

QString str = configuration["bin"].toString().toLatin1();
QByteArray ba = str1.toLatin1();
char *bin = ba.data();

但是你想用 char* 做什么?你在 C++ 中,请改用 std::stringQstring :

#include <string>

std::string bin(configuration["bin"].toString().toLatin1().data());

关于c++ - 为什么我的 char* 无故改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18401345/

相关文章:

Javascript 在 JSON 对象中递归查找

c++ - 使用迭代器构造 QVector 对象

c++ - Qt webkit 小部件错误

c++ - 如何在 x86 程序集中移动两个 float 相乘的结果?

javascript - json stringify 结果获取特定键上的值

c++ - 简单的UDP套接字代码,发送和接收消息

java - 在一个 Json 皮肤中使用多种字体

c++ - 带有网络摄像头 c930e 罗技的 OpenCv

c++ - 为什么 unicode 字符在 C++ std::string 中被同等对待?

c++ - 对成员模板函数的访问控制