将 c++ 字符串转换为常量字符 * 时出现问题

Problems with transforming a c++ string to a const char *

本文关键字:问题 字符 常量 c++ 字符串 转换      更新时间:2023-10-16

我正在尝试从c ++字符串中创建一个指向常量字符数组的指针。 在最后四行中,我将三个字符串添加到一个字符串中。这应该用于创建指向常量数组的指针。然后,应返回此指针以在另一个函数中使用。当我逐步调试时,函数末尾的"cout"显示正确的行为。当我查看 main 函数中的返回值时,它指向垃圾数据。我在返回指针时做错了什么?

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

您返回的指针指向由容器处理的数据,即 c++ 字符串,该字符串超出了范围,因此在函数末尾被解构。要获得所描述的确切行为,您要做的是使用堆分配,如下所示:

char* result = new char[fullID.length()+1];
std::copy(string.c_str(),string.c_str()+fullID.length()+1,result);

你应该直接返回 c++ 字符串,因为我向你保证,你最终会忘记释放这个字符串。

const string checkMultiID(){
return fullID;
}

您可以将静态关键字添加到 fullID,例如:

static string fullID = startID + usbID + endID;

更好的选择是只返回字符串。

编辑:

1201程序警报是正确的。

要避免这种情况,您可以执行以下操作:

static string fullID;
fullID  = startID + usbID + endID;

在这种情况下,在第二次调用第一次调用的 checkMultiID(( 值后将被删除。

如果将函数返回类型更改为 std::string,则可以只返回 fullID,并在另一个函数中调用返回字符串的 c_str(( 方法。

const char * result = checkMultiID().c_str();

这将解决您的问题,这是最简单的解决方案。