2016-12-05 88 views
0

所以說我正在閱讀一個文本文件的二維數組,並且我不知道尺寸是什麼,因此導致我使用malloc。這就是說,這是我的失敗嘗試,希望你們可以跟隨和指導我,因爲我很想知道如何做到這一點!從文本文件讀取2d數組而不知道邊界?

void 2dArray(double **arr, int N, int M) { 
    int i,j; 
    FILE *fp; 
    fp = fopen("array.txt", "r"); 
    for(i=0; i < N; i++) { 
    for(j=0; j < M; j++) { 
     fscanf(fp, "%lf", &arr[i][j]); 
    } 
    } 
} 

int main() { 
    int **array; 
    // How do I initialize this?? 
    // heres my attempt: 
    array = (double **)malloc(sizeof(double*); 
    2dArray(array, N, M); 
    //Where would I get N and M? 
+0

你能澄清這個問題?假設你的文本文件包含12個數字。那麼你怎麼會知道2D數組包含3×4個元素,而不是4×3(或6×2或12×1等)?如果您在問題中包含了文本文件的示例,它可能會有所幫助。 –

回答

0

首先您應該使用已知數據分配資源。爲了知道數據,你應該打開文件並計算你的二維數組的維數。它應該是這樣的:

int **array; 
int *n, *m,i; 
n = malloc(sizeof(int)); 
m = malloc(sizeof(int)); 
findArraySize(n,m); //will find and write array size to n and m 

//start of bad allocation method with lots of seperate resource in actual memory 
array = malloc(n*sizeof(double*)); //allocate resource for pointer to pointer 
for(i = 0 ; i < n ; i++) //allocate resource for each pointer 
    array[i] = malloc(m*sizeof(double)); 
//end of bad allocation method 

//or you can use the allocation method below for better performance and readability 
//(*array)[m] = malloc (sizeof(double[n][m])); 

2dArray(array, *n, *m); 

和你findArraySize功能應該是這樣的:

void findArraySize(int* n, int *m){ 
    int i,j; 
    FILE *fp; 
    char separators[] = " "; 
    char line[256]; 
    char * p; 
    *n = 0; 
    *m = 0; 

    fp = fopen("array.txt", "r"); 

    while(!eof(fp)){ 
     fgets(line, sizeof(line), fp); 
     p = strtok(line, separators); 
     *n += 1; 
     *m = 0; //we assume array is well defined, m is same for each row 
     while (p != NULL) { 
      *m += 1; 
      p = strtok(NULL, separators); 
     } 
    } 
} 
+0

這裏沒有任何理由使用指針指針。只需分配一個二維數組。 'int(* array)[m] = malloc(sizeof(int [n] [m]));'。也沒有理由動態地分配'n'和'm',只需要一個較慢的程序即可實現。 – Lundin

+0

你是對的,但我認爲分別分配所有的指針可以更好地解釋背後的邏輯。 – cokceken

+0

分別分配每個段創建一個指向段的查找表。除了不必要的複雜和出了名的錯誤之外,它有效地阻止了數據緩存的使用,使得程序變得不必要的緩慢。 – Lundin