【发布时间】:2020-01-07 01:29:09
【问题描述】:
我在文件中有一个矩阵,例如:
3
1 2 3
4 5 6
7 8 -9
其中第一行表示方阵顺序。我正在使用以下代码读取文件并将其存储到向量中(为简单起见,我删除了所有 if 检查):
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int read_matrix_file(const char *fname, double *vector)
{
/* Try to open file */
FILE *fd = fopen(fname, "r");
char line[BUFSIZ];
fgets(line, sizeof line, fd);
int n;
sscanf(line, "%d", &n)
vector = realloc(vector, n * n * sizeof *vector);
memset(vector, 0, n * n * sizeof *vector);
/* Reads the elements */
int b;
for(int i=0; i < n; i++) {
// Read the i-th line into line
if (fgets(line, sizeof line, fd) == NULL) {
perror("fgets");
return(-1);
}
/* Reads th j-th element of i-th line into the vector */
char *elem_ptr = line;
for (int j=0; j < n; j++) {
if(sscanf(elem_ptr, "%lf%n", &vector[n*i+j] , &b) != 1) {
perror("sscanf");
return(1);
}
elem_ptr += b;
}
}
fclose(fd);
/* HERE PRINTS OK */
for(int i=0; i<n*n; i++)
printf("%i %f\n",i, vector[i]);
return n;
}
read_matrix_file 接收文件名和doubles 的array 并填充数组,返回矩阵顺序。在此代码块中可以看到预期的用法。
int main(void)
{
const char *fname = "matrix.txt";
double *vector = malloc(sizeof * vector);
int n = read_matrix_file(fname, vector);
/* Here prints junk */
for(int i=0; i<n*n; i++)
printf("%i %f\n",i, vector[i]);
free(vector);
}
问题是,printf 在 read_matrix_file 中工作正常,但在 main 中似乎无效。
我在函数外部分配数组并通过“引用”传递它,但我非常怀疑realloc,不幸的是我不知道如何修复或更好的方法。
【问题讨论】:
-
Google 更新 C 函数中的指针 - 您需要通过
**传递向量。 -
请记住,在 C 中,所有参数都是按值传递。这意味着它们的值被复制到函数的局部参数变量中。修改副本(例如分配给它)不会修改原始副本。请做一些关于在 C 中模拟通过引用传递的研究。
-
另外请注意,您永远不应该将指针分配回您传递给
realloc的指针。如果realloc失败并返回空指针,那么您将丢失原始指针并发生内存泄漏。 -
什么是
start?应该是elem_ptr?