2012-12-07 83 views
1

我已经写了这个小小的怪异代码。 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; 
} 

ouptut:

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

我不太明白为什么downvote或请求关闭... –

回答

4

type是因为它被初始化到一个临时std::string实例的内部构件dangling pointer

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

std::string来自wh的实例ich c_str()的结果立即被破坏。

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

指针type指临时(label.substr(0,f))内的一块数据。该指针的任何使用都是未定义的行为。

0

当通过调用.c_str()得到指向std::string缓冲区的指针时,您不会获取缓冲区。例如,当字符串对象超出范围时,指针将失效。