2012-12-07 86 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緩衝區的指針時,您不會獲取緩衝區。例如,當字符串對象超出範圍時,指針將失效。