所以说我正在从文本文件中读取一个2D数组,而且我碰巧不知道尺寸是什么,从而导致我使用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?
首先,您应该使用已知数据分配资源。为了了解数据,您应该打开文件并计算2D数组的尺寸。看起来应该这样:
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);
}
}
}