gpt4 book ai didi

c - 在不知道边界的情况下从文本文件读取二维数组?

转载 作者:行者123 更新时间:2023-11-30 15:02:38 25 4
gpt4 key购买 nike

假设我正在从文本文件中读取二维数组,并且我碰巧不知道尺寸是多少,因此导致我使用 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?

最佳答案

首先,您应该使用已知数据分配资源。为了了解数据,您应该打开文件并计算二维数组的维度。它应该看起来像这样:

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

关于c - 在不知道边界的情况下从文本文件读取二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40972111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com