2012-09-13 20 views
1

我在修剪字符串末尾的空格時出現Memory Fault錯誤。任何人都可以請幫我解決下面的代碼。使用C語言修剪指針字符串時的存儲器故障

代碼:

char* trimfun(char *st) { 
    int i=0,j; 
    /* Trim spaces and tabs from end:*/ 
    i=strlen(st)-1; 
    while ((st[i]==' ')||(st[i]=='\t')) { 
     i--;  
    } 

    if (i<(strlen(st)-1)) { 
     st[i+1]='\0'; 
    } 
    return st; 
    // free (s); 
    // free (st); 
} 

感謝 拉姆金

+0

看起來不錯,從一目瞭然,但你有兩個無法訪問免費的,未使用的J和不確定秒。 – lynxlynxlynx

+0

傳入的字符串之一可能不是空終止? – Sogger

回答

0

如果整個字符串st是什麼空格?

在這種情況下,while循環:

while((st[i]==' ')||(st[i]=='\t')) { i--; } 

不會在i==0終止!

這可能是您的seg-fault的原因。

嘗試:

while ((i >= 0) && ((st[i]==' ') || (st[i]=='\t')))) { 
    i--;  
}