无法在 C 中动态分配矩阵
我想创建一个函数,读取 .txt 文件的前两个整数作为动态分配矩阵的行数和列数,然后打印该矩阵。 这就是我认为它会起作用的方式。
#include <stdio.h>
#include <stdlib.h>
FILE *openFileR(const char *);
int rows(FILE *);
int cols(FILE *);
void printMat(int **, int, int);
int main()
{
FILE *fp;
fp=openFileR("matrix.txt");
int nrows=rows(fp); int ncols=cols(fp);
printf("Rows:%d\nColumns:%d\n", nrows, ncols);
int **matrix;
matrix=malloc(nrows*(sizeof(int *)));
for(int i=0; i<nrows; i++)
{
matrix[i]=malloc(ncols*sizeof(int));
}
printMat(matrix, nrows, ncols);
return 0;
}
void printMat(int **matrix, int nrows, int ncols)
{
for(int i=0; i<nrows; i++)
{
for(int j=0; j<ncols; i++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int cols(FILE *fp)
{
int columns;
fscanf(fp, "%d", &columns);
return columns;
}
int rows(FILE *fp)
{
int lines;
fscanf(fp,"%d", &lines);
return lines;
}
FILE *openFileR(const char *nome_file)
{
FILE *fp;
printf("File name: %s\n", nome_file);
fp=fopen(nome_file, "r");
if(fp==NULL)
{
printf("Couldn't open file\n");
exit(-1);
}
else
printf("File correctly opened\n");
return fp;
}
问题是我从 printMat 函数获得的输出只是一个由 5 个元素组成的一维数组(ncols 值)而不是矩阵。 我认为矩阵分配有问题,但我不明白它是什么。
矩阵.txt= 4 5
I want to make a function that reads the first two integers of a .txt file as the number of rows and columns of a dynamically allocated matrix and then print the matrix.
Here's how i thought it would work.
#include <stdio.h>
#include <stdlib.h>
FILE *openFileR(const char *);
int rows(FILE *);
int cols(FILE *);
void printMat(int **, int, int);
int main()
{
FILE *fp;
fp=openFileR("matrix.txt");
int nrows=rows(fp); int ncols=cols(fp);
printf("Rows:%d\nColumns:%d\n", nrows, ncols);
int **matrix;
matrix=malloc(nrows*(sizeof(int *)));
for(int i=0; i<nrows; i++)
{
matrix[i]=malloc(ncols*sizeof(int));
}
printMat(matrix, nrows, ncols);
return 0;
}
void printMat(int **matrix, int nrows, int ncols)
{
for(int i=0; i<nrows; i++)
{
for(int j=0; j<ncols; i++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int cols(FILE *fp)
{
int columns;
fscanf(fp, "%d", &columns);
return columns;
}
int rows(FILE *fp)
{
int lines;
fscanf(fp,"%d", &lines);
return lines;
}
FILE *openFileR(const char *nome_file)
{
FILE *fp;
printf("File name: %s\n", nome_file);
fp=fopen(nome_file, "r");
if(fp==NULL)
{
printf("Couldn't open file\n");
exit(-1);
}
else
printf("File correctly opened\n");
return fp;
}
The problem is that the output i get from printMat
function is just a one-dimensional array of 5 elements (the ncols
value) instead of a matrix.
I think there's a problem with the matrix allocation but i don't get what it is.
matrix.txt=4 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论