可视化数组指针的矢量 C++
visual array pointer's vector c++
我是 c++ 的新手,我正在参加检查扫描仪的项目,并且正在使用随扫描仪提供的 API。这是我的代码:
.h 文件 :
#include <iostream>
#include<Windows.h>
#include<vector>
using namespace std;
class Excella
{
public:
vector<char*> getDevicesName();
};
.cpp文件 :
vector<char*> Excella::getDevicesName()
{
DWORD dwResult;
vector<char*> listeDevices;
char pcDevName[128]="";
int i = 6;
// the device's name is stored in the variable 'pcDevName'
while ((dwResult = MTMICRGetDevice(i, (char*)pcDevName)) != MICR_ST_DEVICE_NOT_FOUND) {
dwResult = MTMICRGetDevice(i, (char*)pcDevName);
i++;
listeDevices.push_back((char*) pcDevName);
}
return listeDevices;
}
主.cpp
vector<char*> liste = excella.getDevicesName();
if (liste.empty()!= true)
{
for (vector<char*>::iterator IterateurListe = liste.begin(); IterateurListe != liste.end(); ++IterateurListe)
{ string str(*IterateurListe);
auto managed = gcnew String(str.c_str());
devices->Items->Add(managed);
}
}
else {
MessageBox::Show("The vector is empty");
}
问题是我可以得到正确的设备编号......我只是有一些奇怪的雕刻机。
谢谢你的帮助。
> 这并不奇怪。
char pcDevName[128]="";
将在函数vector<char*> Excella::getDevicesName()
结束时超出范围。因此,您推送到向量的任何指向此的指针都将不再有效。从形式上讲,程序的行为是未定义的。
改用std::vector<std::string>
要简单得多。值得注意的是,这是您必须进行的唯一更改:push_back((char*) pcDevName)
将获取pcDevName
的值副本(这就是std::string
构造函数的工作方式)。 不过,删除不必要的(char*)
转换。
在这里:
listeDevices.push_back((char*) pcDevName);
您正在将指向堆栈数组的指针推送到 listeDevices 中。这有两个问题 - 市长一个是一旦你的getDevicesName函数结束,这些指针是无效的,并且它们的使用是未定义的,另一个是在循环的每次迭代中,你都会覆盖pcDevName以及存储的指针内容。
你应该做的是让listeDevices存储std::string,即。 std::vector<std::string>
,然后您可以使用listeDevices.push_back((char*) pcDevName);
将名称安全地存储在向量中。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '