【发布时间】:2020-01-20 14:32:44
【问题描述】:
我正在尝试从 c++ 字符串创建一个指向常量字符数组的指针。 在最后四行中,我将三个字符串添加到一个字符串中。这应该用于创建指向常量数组的指针。然后应该返回该指针以在另一个函数中使用。当我逐步调试时,函数末尾的“cout”显示了正确的行为。当我查看主函数中的返回值时,它指向垃圾数据。返回指针时我做错了什么?
const char *checkMultiID(void){
string startID = "USB0::0x2A8D::0x0101::";
string usbID = "MY54500604";
string endID = "::0::INSTR";
char answerID;
int correctFunctionInput = 0;
cout << "ID = " << usbID << "? [Y/N]" << endl;
scanf("%c", &answerID);
while(correctFunctionInput == 0){
if ((answerID == 'Y') || (answerID == 'N')){
correctFunctionInput = 1;
}
else{
cout << "Incorrect Input. Please repeat." << endl;
scanf("%c", &answerID);
}
}
if (answerID == 'N'){
cout << "Please Type in the ID like MY..." << endl;
getline (cin, usbID);
}
string fullID = startID + usbID + endID;
const char *idChar = &fullID[0];
cout << idChar << endl;
return idChar;
}
【问题讨论】:
-
那是因为字符串在函数末尾超出范围,所以指向字符串数据的
char*之后将不再有效。 -
所以我需要创建一个全局字符串?
-
@Alex 直接返回整个
std::string。 -
好的,它正在使用全局字符串。还有其他我没有想到的不需要全局变量的解决方案吗?
标签: c++ pointers char constants