2013-01-05 29 views
2

我有字符串數組,我想複製數組中的字符串。它工作的時間比程序停止工作,並且我知道問題在於複製字符串。因爲如果我評論與copiyng一致,程序工作正常。 這裏是我的代碼:字符串數組,寫入數據失敗C

FILE *fsource = fopen(source, "rb"); 
char fname[256], **files, mybuf[BUFSIZ]; 
files = allocate2d(files, count_files); 

clear(fname); 

reading = fread(mybuf, 1, BUFSIZ, fsource); 
while(reading) 
{ 
    for(i = 0; i < reading; i++) 
    { 
     if(mybuf[i] == 20) 
     { 
      while(1) 
      { 
       if(i < reading) 
       { 
        if(mybuf[i] == 0) 
        { 
         clear(files[ifiles]); 
         strcat(files[ifiles++], fname); // here is problem :(
         //append_string(files[ifiles++], fname); // also doesn't work 

         clear(fname); 
         break; 
        } 

        append_char(fname, mybuf[i++]); 
       } 
       else 
       { 
        break; 
       } 
      } 
     } 

     clear(fname); 
    } 

    reading = fread(mybuf, 1, BUFSIZ, fsource); 
} 

char** allocate2d(char **arr, unsigned int size) 
{ 
    unsigned int i = 0; 
    arr = malloc(size * sizeof(char)); 

    for(i = 0; i < size; i++) 
    { 
     arr[i] = malloc(256); 
    } 

return arr; 
} 

回答

1

allocate2d

arr = malloc(size * sizeof(char)); 

應該

arr = malloc(size * sizeof(char*)); 

,因爲要爲size指針分配空間。

而且

arr[i] = malloc(256); 

最好是

arr[i] = calloc(256, sizeof(char)); 

,以確保strcat找到一個0字符。 (注意:sizeof(char)只是寫入1的另一種方法。)

+0

這是真正的我需要,非常感謝:) – Azure

1

您必須修復allocate2d()中的分配。如果你想分配一個指針陣列

arr = malloc(size * sizeof(char*));