2016-01-20 69 views
0

我是新来的c + +,我在一个检查扫描器的项目,我使用的扫描仪提供的API。这里是我的代码:数组指针的向量C++

.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; 
    } 

的main.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"); 
     } 

的问题是,我可以得到正确的设备号码..我只是有一些怪异的字符。

谢谢你的帮助。

+0

你能否提供一些细节?你会得到什么样的怪异人物? – swinefish

+0

对于一个'pcDevName'已经是'char *'所以摆脱不需要的'char *'强制转换。 –

+0

对于两种情况,在将'pcDevName'推入向量之前,您从不检查'dwResult'的结果以确保''MTMICRGetDevice'成功。如果失败了,这将解释为什么你看到未初始化的垃圾。 –

回答

1

这并不奇怪。

char pcDevName[128]="";将在功能vector<char*> Excella::getDevicesName()的末尾超出范围。所以任何你已经推送到vector的指针都不再有效。从形式上讲,你的程序的行为是undefined

取而代之,使用std::vector<std::string>要简单得多。值得注意的是,这是你必须做出的唯一改变:push_back((char*) pcDevName)将采用pcDevName的价值副本(这就是std::string构造函数的工作方式)。尽管放弃不必要的(char*)剧组。

+0

谢谢,问题解决了 – user5712010

1

这里:

listeDevices.push_back((char*) pcDevName); 

你是推入listeDevices一个指针到堆叠阵列。有两个问题 - 市长之一是,一旦你的getDevicesName函数结束,这些指针是无效的,使用它们是未定义的,另一个是在你的循环的每次迭代中,你覆盖pcDevName以及你存储的指针内容。

你应该做的是让listeDevices存储std :: string,即。 std::vector<std::string>,然后您可以使用listeDevices.push_back((char*) pcDevName);将您的名字安全地存储在向量中。

+0

谢谢你的帮助 – user5712010