我正在编写一个程序,需要在函数中不断地处理矩阵。这是其中的一个函数,它的作用是打开一个外部数据集文件,该文件中的数据以制表符分隔,打开文件并将数据保存到矩阵M中。我知道这个矩阵由6列组成,但行数未知。我知道错误出现在声明矩阵时,因为函数需要返回矩阵,所以必须使用指针来声明。
//type float** since it will return a matrix
float **carga_archivo(char *nombre_archivo)
{
float **M=(float **)malloc(6*sizeof(float*)); //error should be here
int i=0;
FILE *archivo; //FILE type pointer to open the external file
archivo=fopen(nombre__archivo,"r"); //Opens the file in the address indicated
//"nombre_de_archivo" is a variable
while(!feof(archivo)) //Browses the file row per row till the end of it
{
//saves the data in its corresponding place in the matrix
fscanf(archivo,"%f\t%f\t%f\t%f\t%f\t%f\n",
&M[0][i],&M[1][i],&M[2][i],&M[3][i],&M[4][i],&M[5][i]);
i++;
}
tam=i;
fclose (archivo); //closes the file
return M;
}
我需要的是声明矩阵的正确方法。
附言:我在代码中记录了主要内容,以帮助需要类似东西的人。欢迎任何纠正。
更新:应用了评论中提出的一些更改,效果更好了。这是我为该函数制作的新代码。
float **carga_archivo(char *nombre_archivo)
{
int i=0;
float P[300][6];
FILE *archivo;
archivo=fopen(nombre_archivo,"r");
while(!feof(archivo))
{
i++;
//this was just so the feof function could browse row per row
//instead of character per character
scanf("%f\t%f\t%f\t%f\t%f\t%f\n",
&P[0][i],&P[1][i],&P[2][i],&P[3][i],&P[4][i],&P[5][i]);
printf("%i\n",i);
}
tam=i;
printf("%i",tam);
int filas = 6;
int columnas = tam;
float **M;
M = (float **)malloc(filas*sizeof(float*));
for (i=0;i<filas;i++)
M[i] = (float*)malloc(columnas*sizeof(float));
for (i = 0; i < columnas; ++i)
fscanf(archivo,"%f\t%f\t%f\t%f\t%f\t%f\n",
&M[0][i],&M[1][i],&M[2][i],&M[3][i],&M[4][i],&M[5][i]);
fclose (archivo);
return M;
}
新的问题是当调用该函数时,程序实际上会编译,但在运行并调用函数时程序崩溃停止。 这里是调用该函数的代码部分。
int main()
{
int i,j;
char *nombre_archivo="Agua_Vapor.txt";
float **agua_vapor=carga_archivo(nombre_archivo);
for (i = 0; i < 6; i++)
{
for (j = 0; i < tam; i++)
printf("%f ", agua_vapor[i][j]);
printf("\n");
}
return 0;
}
char nombre_archivo
是错误的。文件名不止一个字符。此外,如果行数未知--您需要将该信息返回给调用者,可能作为返回值(同时传递指向函数的指针,该指针在函数返回后将指向浮点数数组)。 - John Coleman