2016-12-05 43 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