奇怪的const char*行为

Strange const char* behaviour

本文关键字:行为 char const      更新时间:2023-10-16

getTypename是std :: string,以下代码

printf("%#xn", proto->GetTypeName().c_str());
printf("%sn", proto->GetTypeName().c_str());
const char *res = proto->GetTypeName().c_str();
printf("%#xn",res);
printf("%sn",res);

产生此输出:

0x90ef78
ValidTypeName
0x90ef78
ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■←ЬЬQщZ

地址始终相同;以下代码(行交换)

const char *res = proto->GetTypeName().c_str();
printf("%#xn",res);
printf("%sn",res);
printf("%#xn", proto->GetTypeName().c_str());
printf("%sn", proto->GetTypeName().c_str());

产生此输出,地址总是不同的:

0x57ef78
  Y
0x580850
ValidTypeName

我在做什么错?

strlen(res)

返回无效的大小,所以我什至无法strcpy。

yourgetTypename函数正在返回std ::字符串,您正在调用C_ST,以获取该字符串中的内部数据指针。

因为这是暂时的std ::字符串,您将在语句末尾删除

的结尾
const char *res = proto->GetTypeName().c_str();

,但您仍然指向现在已删除的数据。

编辑:将代码更改为: -

const std::string& res = proto->GetTypeName(); 

并在printf中的该字符串上呼叫.c_str()这样: -

printf("%#xn",res.c_str());
printf("%sn",res.c_str());

将临时参考分配给该临时的寿命与参考的寿命相同...

更好的是,只需使用std :: string和iostream即可打印并停止在不必要的情况下用低级指针弄乱:)