c++ - 奇怪的一段代码

标签 c++

我写了这段奇怪的代码。 type 怎么可能在它的 2 个 printf 之间改变??

提前致谢

int main()
{
    string label = string("faults_team_A_player_12");

    size_t f = label.find('_');

    const char *type = label.substr(0,f).c_str();
    const char team = label.at(f+sizeof("team_"));

    printf("type = %s\n",type);

    int n;
    size_t l = label.length()-label.find_last_of('_');

    int x = sscanf((char *)label.substr(label.find_last_of('_'),l).c_str(),"_%d",&n);
    printf("type = %s\n",type);
    printf("team = %c\n",team);
    printf("player = %d\n",n);

    return 0;
}

输出:

type = faults
type = _12
team = A
player = 12

最佳答案

typedangling pointer因为它被初始化为临时 std::string 实例的内部成员:

const char *type = label.substr(0,f).c_str();

从中获取c_str()结果的std::string实例被立即销毁。

关于c++ - 奇怪的一段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13766479/

相关文章:

Android NDK - 命名空间 'function' 中没有名为 'std' 的类型

c++ - 如何在 C++ 中创建具有子函数的对象?

C++ pugiXML,在节点中的第一个子节点之前附加一个子节点

c++ - 尝试将 GTK+ 窗口渲染为图像

c++ - 没有模板参数?

c++ - boolean 值在分配时应该被截断为 true 还是 false?

c++ - 将唯一的 int 数组映射到范围 0..n 的索引的哈希函数

c++ - 将 cuda 内存处理包装在一个类中会导致损坏的内存地址

c++ - "invalid use of member"尝试使用我的功能时

c++ - Monodevelop C++ 调试问题