问题描述
在矩阵中。 c我有
struct matrix{
int row;
int col;
int *a;
};
Matrix* allocateMemory(int m,int n) {
Matrix* mat = (Matrix*) malloc(sizeof(Matrix));
if (mat == NULL) {
return NULL;
}
mat->row = m;
mat->col = n;
mat->a = (int*)calloc(m*n,sizeof(int));
return m;
}
虽然在 matrix.h 我有
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
typedef struct matrix Matrix;
Matrix* allocateMemory(int m,int n);
//...
int printMatrix(Matrix* mat);
int transpose(Matrix* mat);
#endif // MATRIX_H_INCLUDED
我正在处理矩阵的 ADT,但我坚持使用打印功能。我想创建一个函数
int printMatrix(Matrix* mat)
所以在 main.c 中我会有类似的东西
int i,j;
for (i = 0; i < row; i++){
for(j = 0; j < col; j++){
printf("%d ",printMatrix(mat));
}
printf("\n");
}
这意味着我想要主函数中的 printf,而不是函数中的 printf,但我只能这样做
void printMatrix(Matrix* mat){
int i,j,k;
for (i = 0; i < mat->row; i++){
for(j = 0; j < mat->col; j++){
k = i*mat->col + j;
printf("%d ",mat->a[k]);
}
printf("\n");
}
}
它确实打印了矩阵,但似乎不正确。转置矩阵函数也是如此,它确实正确打印了转置矩阵,但我想要一个
int transpose(Matrix* mat)
所以我会在 main 中使用函数 printMatrix 来打印转置,但我只能这样做
void transpose(Matrix* mat){
int i,k;
for (i = 0; i < mat->col; i++){
for (j = 0; j < mat->row; j++){
k = j*mat->row + i;
printf("%f ",mat->a[k]);
}
printf("\n");
}
}
如何创建 int 函数来打印矩阵?
我还在学习ADT,但我缺乏理解所以我不能做这个功能?
解决方法
这是我最喜欢的评论的开头。
更多的风格提示...
不要不要投射 malloc
[et. ]
更惯用的是(例如):
Matrix *mat = malloc(sizeof(*mat));
我意识到在学校里,他们教使用(例如)i,j,k
,但尝试使用更具描述性的名称(例如)row,col,off
。
并且,使参数也具有描述性:
Matrix *allocateMemory(int row,int col)
这是一个重构版本[带有一些样式清理]:
#include <stdio.h>
#include <stdlib.h>
typedef struct matrix {
int row;
int col;
int *a;
} Matrix;
Matrix *
allocateMemory(int row,int col)
{
Matrix *mat = malloc(sizeof(*mat));
if (mat == NULL) {
perror("malloc");
exit(1);
}
mat->row = row;
mat->col = col;
mat->a = calloc(row * col,sizeof(*mat->a));
if (mat->a == NULL) {
perror("calloc");
exit(1);
}
return mat;
}
void
printMatrix(Matrix *mat)
{
int row,off;
for (row = 0; row < mat->row; row++) {
for (col = 0; col < mat->col; col++) {
off = (row * mat->col) + col;
printf("%d ",mat->a[off]);
}
printf("\n");
}
}
void
matrix_fill(Matrix * mat)
{
int row,off;
int val = 1;
for (row = 0; row < mat->row; row++) {
for (col = 0; col < mat->col; col++) {
off = (row * mat->col) + col;
mat->a[off] = val++;
}
}
}
void
transpose_copy(Matrix *matout,Matrix *matin)
{
int row,col;
int inoff,outoff;
for (row = 0; row < matin->row; row++) {
for (col = 0; col < matin->col; col++) {
inoff = (row * matin->col) + col;
outoff = (col * matout->col) + row;
matout->a[outoff] = matin->a[inoff];
}
printf("\n");
}
}
Matrix *
transpose_new(Matrix *matin)
{
Matrix *matout = allocateMemory(matin->col,matin->row);
transpose_copy(matout,matin);
return matout;
}
int
main(void)
{
Matrix *matin = allocateMemory(2,3);
matrix_fill(matin);
printf("Original:\n");
printMatrix(matin);
Matrix *matout = transpose_new(matin);
printf("Transposed:\n");
printMatrix(matout);
return 0;
}
这是程序输出:
Original:
1 2 3
4 5 6
Transposed:
1 4
2 5
3 6