在while循环的下一次迭代中重写Const char *

const char * overwritten in next iteration of while loop

本文关键字:迭代 一次 重写 Const char 循环 while      更新时间:2023-10-16

首先,一切都发生在do{}while循环中的if{}语句中。我有一个包含const char指针的结构体。我试图将信息放入每次迭代具有新字符串值的临时结构体中,然后将此结构体推入所述结构体的向量中,以便当函数退出时,向量填充不同的结构体对象。

do{
   if()
   {
     sound_device_t newDevice;  //<--- Why is this the same mem address each iteration?
                                //I thought it would be destroyed when it's scope was (the if block)

     const char * newPath;
     someFunction(&newPath); //puts a string into newPath
     newDevice.firstString = newPath;   //<-- This works.
     QString otherPath(const char *);
     //...some QString manipulation...//
     newDevice.secondString = otherPath.toLocal8Bit().data();  //<--this doesn't
     vector_of_structs -> push_back(newDevice);
   }
}while (...)

我的印象是push_back将实参结构体的值复制到自己的版本中。为什么QString给我的问题?我正在使用QString,因为它有一些很好的字符串操作函数(即插入和部分),但我会交换它,如果我需要的东西,工作。

我也试过把QString的数据放入一个char *,然后将其字符串化到结构体中,但结果相同。每次迭代都会重写newDevice.secondString。

QByteArray::data()仅在ByteArray未改变的情况下有效。销毁临时文件正在改变。

换句话说,在newDevice.secondString = otherPath.toLocal8Bit().data();的分号之后,toLocal8Bit返回的QByteArray被销毁,存储的数组delete d。

您的代码有几个问题:

  • if语句不带条件

  • 无效构造:QString otherPath(const char *);你可能需要一个"otherPath"变量,类似于"newPath"。

  • 您正在将qt类型与std容器混合。你应该看一下QStringList

  • 不必要的指针使用:newDevice。

最后一个尤其重要,因为您在下一次迭代之前销毁了otherPath。解决方案是在那里使用深拷贝。

我会这样写:

do {
   if(cond) {
     sound_device_t newDevice;    
     const char * newPath;
     someFunction(&newPath);
     newDevice.firstString = newPath;
     // Get other path
     QString otherPath(otherPath);
     //...some QString manipulation...
     newDevice.secondQString = otherPath;
     // or: strcpy( newDevice.secondString, otherPath.toLocal8Bit().data());
     vector_of_structs->push_back(newDevice);
   }
} while (...)

也就是说,根据您要做的事情,QtMultiMedia可能更好地用于您的声音设备目的。只要有dbus,还有一个QtDBus附加模块。

谢谢大家的帮助。我只做了一个调整就得到了原始代码:

newDevice.secondString = otherPath.toLocal8Bit().data();

改为

newDevice.secondString = strdup(otherPath.toLocal8Bit().data());

直接分配缓冲区,就像@ratchet freak建议的那样。strcpy()不起作用,因为它仍然连接newDevice。与toLatin1().data()一样,使用QByteArray . secondString