奇怪的const char*行为
Strange const char* behaviour
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即可打印并停止在不必要的情况下用低级指针弄乱:)
相关文章:
- strncpy之后的char数组的错误行为
- 对象初始化后在C++中显示 char 数组时的异常行为
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 从 std::string 到 std::array<char,size> 的 memcopy 额外数据是否是一种未定义的行为?
- 将结构 std::memcpy 转换为具有足够容量的 std::vector 是未定义的行为<char>吗?
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- 通过 char* 缓冲区读取 int 的行为是不同的,无论是正数还是负数
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 使用模板化方法的 char 意外行为
- 关于'char'的奇怪程序行为
- 意外行为将字符串转换为const char*
- 我不明白这个例子中char的行为
- 使用 char16_t 类型作为 char[] 数组,并通过 reinterpret_cast<> 重新转换它。我的代码是否有未定义的行为?
- 在C++中,是否定义了删除基元类型(如通过 char* uint32_t)的行为
- C++:带有cout和指向char的指针的无法解释的行为
- 标准的C 行为对未签名的INT转换的签名char
- 将const char *传递给file.open(),奇怪的行为
- 奇怪的const char*行为
- 指针行为从void*到unsigned char*的奇怪情况
- 手动将char转换为int-奇怪的行为