2012-06-10 101 views
0

我創建這段代碼在C逐行讀取文本文件線和每行存儲到陣列的位置:C:如何將字符串存儲到「char * myArray [100]」數組中?

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

static const int MAX_NUMBER_OF_LINES = 100000; 
static const char filename[] = "file.csv"; 

int main (void) 
{ 

    // Read file and fill the Array 
    char *myArray[MAX_NUMBER_OF_LINES]; 
    int numberLine = 0; 
    FILE *file = fopen (filename, "r"); 
    if (file != NULL) 
    { 
     char line [128]; 
     while (fgets (line, sizeof line, file) != NULL) 
     { 
      myArray[numberLine] = line; 
      numberLine++;  
     } 
     fclose (file); 
    } 

    // Print the Array 
    for (int i = 0; i<numberLine; i++) 
    { 
    printf("%d|%s", i, myArray[i]); 
    } 
} 

但是打印陣列時,它是空的。我究竟做錯了什麼?

+0

該數組只能存儲指向字符串的指針,它不能存儲字符串。究竟是哪裏出了問題,每個元素指向相同的變量。考慮strdup()。 –

+0

當你嘗試打印它時,該變量不再存在,因爲它是「if」塊的本地。 –

+0

投票了任何有用的答案,並選擇最佳答案作爲接受 –

回答

4

因爲您需要將行復制到陣列中的緩衝區中。

您需要爲陣列的每個元素中的字符串分配空間,然後使用類似strncpy的東西將每個line移動到每個myArray插槽中。

在您當前的代碼中,您只是將相同的參考 - 到您的line緩衝區 - 複製到每個陣列插槽中,因此最後,myArray的每個插槽應指向內存中的相同字符串。

按鄰省的建議,會的strdup節省了一步,如果它是可用的,所以嘗試:

myArray[i] = strdup(line); 

沒有錯誤處理有,請參閱該文檔爲strncpystrdup

或者你可以只添加一個維度myArray

char myArray[MAX_NUMBER_OF_LINES][100]; 
+2

如果他的系統有'strdup',我認爲'myArray [numberLine] = strdup(line);'應該工作。 – Shoaib

1

你需要的所有字符串真正分配空間,但不僅爲指針,以不存在的字符串。在你的例子中,所有分配的指針都指向變量,這超出了範圍。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

static const int MAX_NUMBER_OF_LINES = 100000; 
static const int MAX_LINE_LENGTH = 127; 
static const char filename[] = "file.csv"; 

int main (void) 
{ 

    // Read file and fill the Array 
    char myArray[MAX_NUMBER_OF_LINES][MAX_LINE_LENGTH + 1 /* for 0 byte at end of string */]; 
    int numberLine = 0; 
    FILE *file = fopen (filename, "r"); 
    if (file != NULL) 
    { 
     while (fgets (myArray[numberLine], MAX_LINE_LENGTH + 1, file) != NULL) 
     { 
      numberLine++;  
     } 
     fclose (file); 
    } 

    // Print the Array 
    for (int i = 0; i<numberLine; i++) 
    { 
    printf("%d|%s", i, myArray[i]); 
    } 
} 
1

陣列炭*點到線chararray,但你應該保存的每一行中的陣列和指向myArray的[數軸]將其:


#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

static const int MAX_NUMBER_OF_LINES = 100000; 
static const char filename[] = "file.csv"; 

int main (void) 
{ 

    // Read file and fill the Array 
    char *myArray[MAX_NUMBER_OF_LINES]; 
    int numberLine = 0; 
    FILE *file = fopen (filename, "r"); 
    if (file != NULL) 
    { 
     char line [128]; 
     while (fgets (line, sizeof line, file) != NULL) 
     { 
      //refinement is hre 
      myArray[numberLine] = (char*)malloc(sizeof line); 
      strcpy(myArray[numberLine], line); 
      numberLine++;  
     } 
     fclose (file); 
    } 

    // Print the Array 
    for (int i = 0; i<numberLine; i++) 
    { 
    printf("%d|%s", i, myArray[i]); 
    free(myArray[i]) 

    } 
} 
+0

分配的內存應該被釋放。 – Ruben

+0

最新的問題是什麼? –

+0

好的,免費()已添加 –

相關問題