我正在制作一个程序,我必须不断地在函数中使用矩阵工作,这是许多函数中的一个,这个函数应该打开一个外部文件,它是一个数据设置,其中的数据用表格分开,它打开文件并将数据保存在矩阵M中,我知道这个矩阵由6列组成,但行号是未知的,我知道错误是我声明矩阵的地方,它必须用指针声明,因为该函数返回矩阵。从函数中返回一个矩阵C
//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;
}
我需要的是正确的方法来声明矩阵。
P.S.我记录了代码中的主要内容,以便可以帮助需要类似内容的人。
欢迎任何更正。
更新: 进行一些改动的意见建议,并更好地工作,这里是新的代码我名手该功能
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;
}
'焦炭nombre_archivo'是错误。一个文件名有多个字符。另外,如果行数未知 - 您需要将该信息返回给调用者,也许作为返回值(同时将函数的指针传递给将在函数返回后指向浮点数组的函数 –
你,我只是编辑你提到的第一个问题,但我觉得我不跟你在第二部分,我不是很熟悉的指针,也许一个例子可以帮我一个小 –
如果你不知道事先的行数,则需要通过文件扫描至少一次得到这个数字,*然后*分配*总*的内存量需要从文件中的数据存储你的数据,然后读入到您的矩阵。这需要通过文件读取的两倍。 – Evert