2015-01-16 26 views
0

我試圖將一個字符串拆分成多個小字符串(nb大小)。 但它不工作,因爲我想:爲什麼strincpy在我的for循環無效?

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 
#include <sys/types.h> 
int main(int argc, char *argv[]) { 
    char *source = argv[1]; 
    int taille=0; 
    int i=0; 
    int k; 
    int nb = 5; 
    char dest[strlen(source)/nb][nb]; 
    while(i<strlen(source)) 
    { 
    char *src = &source[i]; 
    strncpy(dest[taille],src,nb); 
    i=i+nb; 
    taille++; 
    } 

    for(k = 0 ; k <8;k++) 
    { 
    printf("\t%s\n",dest[k]); 
    } 
} 

這裏是跟蹤:

[email protected]:~/codeFTP/code/serveur$ ./a.out " bonjour cocoman, tu me donne20 balles?" 
    bonjour cocoman, tu me donne20 balles? 
    our cocoman, tu me donne20 balles? 
    ocoman, tu me donne20 balles? 
    n, tu me donne20 balles? 
    me donne20 balles? 
    onne20 balles? 
    0 balles? 
    les? 

但最奇怪的是,如果我走了一段時間(或thefor,我嘗試兩種),它的工作(通過起飛,而我的意思是用適當的值而不是使用循環寫入strncpy 8次)。 感謝您的關注。

+0

你是怎麼編譯這段代碼的?你應該創建一個const大小的數組,或者爲它分配內存!在這一行中: 「char dest [strlen(source)/ nb] [nb];」當strlen(源代碼)在運行時指定時 ! – mostafa88

回答

3

strncpy不會終止字符串。你需要自己做。當你printf第一個時,printf永遠不會找到null,並開始打印內存中發生的任何事情。因爲它們在一個數組中,所以它看到的下一個字節是下一個字符串的第一個字節。這一直持續到最後一個字符串爲止,因爲strncpy實際上看到了源字符串的結尾。

你需要改變你的聲明持有每串多一個字節爲空字符:

char dest[strlen(source)/nb][nb + 1]; 

,然後手動空終止每個子副本後:

dest[taile][nb] = 0; 

我不確定爲什麼展開循環工作 - 當你重寫它時,你的其他邏輯可能會有輕微的變化。

編輯補充:另外,正如Gopi在他們的回答中所說的,你的數學計算可以找到字符串的數量。如果字符串長度不是nb的完美倍數,那麼你的數組太小,而你正在調用未定義的行爲。最簡單的解決方案也是向該維度添加一個。你的循環是安全的,因爲它基於strlen,而不是你計算的子串的數量。

char dest[strlen(source)/nb + 1][nb + 1]; 
+0

似乎通過添加您的建議: 'char dest [strlen(source)/(nb + 1)] [nb + 1]; ..... dest [taille] [nb] = NULL;' Thanksa lot – Stikmou

+0

@Stikmou傳遞一些長度小於5的字符串,你會看到UB是不是? – Gopi

+0

@Stikmou不是'strlen(source)/(nb + 1)' - 實際上比以前更糟!它需要是'strlen(source)/ nb + 1',相當於'(strlen(source)/ nb)+ 1'。 @Gopi能否在短期投入中解釋UB?我現在沒有看到它,但我可以輕鬆地忽略一些東西。 – Katie

1

沒有與

strlen(source)/nb爲索引一個潛在的問題,並與strlen(source)這將有最低行和你正在做以下

while(i<strlen(source)) 
    { 
    char *src = &source[i]; 
    strncpy(dest[taille],src,nb); 
    i=i+nb; 
    taille++; 
    } 

現在dest[taille]註定是陣列出並確保

strncpy()不會\0終止字符串。

基本情況:傳遞一些長度小於5的字符串,並且你有UB。代碼中有多個這樣的潛在錯誤。

相關問題