从文件中读取二维数组并返回C原因呢程序
时间: 2023-12-03 14:46:49 浏览: 21
以下是从文件中读取二维数组并返回的C语言程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
int** read_array(const char* filename, int* rows, int* cols) {
FILE* fp = fopen(filename, "r");
if (!fp) {
printf("Failed to open file %s\n", filename);
return NULL;
}
fscanf(fp, "%d %d", rows, cols);
int** arr = (int**) malloc(*rows * sizeof(int*));
for (int i = 0; i < *rows; i++) {
arr[i] = (int*) malloc(*cols * sizeof(int));
for (int j = 0; j < *cols; j++) {
fscanf(fp, "%d", &arr[i][j]);
}
}
fclose(fp);
return arr;
}
int main() {
int rows, cols;
int** arr = read_array("input.txt", &rows, &cols);
if (arr) {
printf("Array read from file:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
}
return 0;
}
```
在上述程序中,`read_array`函数接受文件名、指向行数和列数的指针,并返回一个指向二维数组的指针。函数首先打开文件,读取行数和列数,然后分配内存以存储数组。接下来,函数循环读取文件中每个元素,并将其存储在相应的内存位置中。最后,函数关闭文件并返回指向数组的指针。
在主函数中,我们调用`read_array`函数,并在成功读取数组后打印其内容。最后,我们释放动态分配的内存以避免内存泄漏。