在while循环的下一次迭代中重写Const char *
const char * overwritten in next iteration of while loop
首先,一切都发生在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
- 在一次迭代中从 txt 文件中读取多行
- 高级选择排序 - 在一次迭代中搜索两个元素
- 在unordered_multimap中精确迭代一次每个键的有效方法
- foor 循环的最后一次迭代中的指针更改
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- ifstream不会在下一次迭代中打开文件
- C++如何使用lambda表达式来捕获上一次迭代的值
- 如何强制循环执行另一次迭代到零并关闭循环
- 在循环工作时,首先将两个文件读为向量,但仅次于迭代一次
- 迭代一组和擦除元素
- 循环在此代码中仅迭代一次,而在另一个代码中正确迭代
- 臂组件:循环只会迭代一次,然后较低误差
- C :优雅地迭代一组数字
- C++ 迭代一项 - UB 或定义的行为
- 为什么将复制构造器称为25次,而插入循环仅迭代10次
- C++ - 解析文件在最后一行迭代两次
- C++:跟踪代码中的迭代(n次迭代后执行x)/用户输入
- 如何在c++映射中迭代一组特定的键
- 如何在一个完整图的每条边上迭代一次
- For循环不迭代指定次数(少迭代1次)