在不知道边界的情况下从文本文件中读取2d数组?

时间:2016-12-05 10:31:28

标签: c arrays malloc

所以说我正在从文本文件中读取一个二维数组,而且我不知道维度是什么,因此导致我使用malloc。话虽这么说,这是我失败的尝试,希望你们可以跟进并指导我,因为我很想知道如何做到这一点!

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?

1 个答案:

答案 0 :(得分:1)

首先,您应该使用已知数据分配资源。为了知道数据,您应该打开文件并计算二维数组的尺寸。它应该是这样的:

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);
        }
    }
}