并没有完全按照题目要求写,算法的关键就是把 w 和 h 调换dest->data[h * dest->width + w] = matrix->data[w * matrix->width + h];
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
size_t width;
size_t height;
} matrix_t;
static matrix_t *new_matrix(size_t width, size_t height) {
matrix_t *matrix = malloc(sizeof(*matrix));
if(!matrix) return NULL;
matrix->width = width;
matrix->height = height;
matrix->data = malloc(sizeof(*matrix->data) * matrix->width * matrix->height);
if(!matrix->data) {free(matrix); return NULL;}
return matrix;
}
matrix_t *matrix_init(FILE *fp, size_t width, size_t height) {
matrix_t *matrix = new_matrix(width, height);
if(!matrix) return NULL;
for(size_t h = 0; h < matrix->height; ++h) {
for(size_t w = 0; w < matrix->width; ++w) {
fscanf(fp, "%d", &matrix->data[h * matrix->width + w]);
}
}
return matrix;
}
void matrix_deinit(matrix_t *matrix) {
if(matrix) free(matrix->data);
}
void matrix_print(const matrix_t *matrix) {
if(!matrix) return;
for(size_t h = 0; h < matrix->height; ++h) {
for(size_t w = 0; w < matrix->width; ++w) {
printf("%d ", matrix->data[h * matrix->width + w]);
}
printf("\n");
}
}
matrix_t *matrix_transform(const matrix_t *matrix) {
if(!matrix) return NULL;
if(matrix->width != matrix->height) return NULL;
matrix_t *dest = new_matrix(matrix->width, matrix->height);
if(!dest) return NULL;
for(size_t h = 0; h < matrix->height; ++h) {
for(size_t w = 0; w < matrix->width; ++w) {
dest->data[h * dest->width + w] = matrix->data[w * matrix->width + h];
}
}
return dest;
}
int main(void) {
matrix_t *a = matrix_init(stdin, 3, 3);
matrix_t *b = matrix_transform(a);
matrix_print(b);
matrix_deinit(b);
matrix_deinit(a);
return 0;
}
|