将 c++ 字符串转换为常量字符 * 时出现问题
Problems with transforming a c++ string to a const char *
我正在尝试从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();
这将解决您的问题,这是最简单的解决方案。
相关文章:
- 从矢量C++读取字符时出现问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- C++理解计算字符变量的问题
- 将十六进制值设置为用于填充的字符变量时出现问题
- 编写 cin.get() 以接收字符数组时出现问题
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 字符 * 未从重载运算符或内存管理问题正确返回
- 将utf16宽std::wstring转换为utf8窄std::string以获得罕见字符时出现问题
- 我在使用字符的函数时遇到了一些问题
- 用wchar_t处理 unicode 字符好吗?它不会引起任何问题吗?
- 将 c++ 字符串转换为常量字符 * 时出现问题
- C++程序,将整数输入转换为字符的问题
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- C++ 初级面试问题:仅使用字符指针压缩字符序列的功能
- 通过比较字符设置字符串时出现问题
- 我的编辑距离递归代码中的字符类型有问题
- 获取“boost::文件系统::p ath”字符指针时出现问题
- C Unicode UTF-8解码字符的问题
- 类型转换问题:字符数组的元素转换为整数变量