可视化数组指针的矢量 C++

visual array pointer's vector c++

本文关键字:C++ 数组 指针 可视化      更新时间:2023-10-16

我是 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);将名称安全地存储在向量中。