1、直接在函数中实现矩阵加法
最简单直接的方法,在一个函数使用for
循环中对矩阵进行操作。
#include <stdio.h>
#define ROWS 3
#define COLS 3
void addMatrices(int mat1[ROWS][COLS], int mat2[ROWS][COLS], int result[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
int main() {
int mat1[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int mat2[ROWS][COLS] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[ROWS][COLS];
addMatrices(mat1, mat2, result);
printf("结果:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
2、使用指针实现矩阵加法
通过指针来操作数组,进行矩阵加法。
#include <stdio.h>
#define ROWS 3
#define COLS 3
void addMatrices(int *mat1, int *mat2, int *result, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
*(result + i * cols + j) = *(mat1 + i * cols + j) + *(mat2 + i * cols + j);
}
}
}
int main() {
int mat1[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int mat2[ROWS][COLS] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[ROWS][COLS];
addMatrices((int *)mat1, (int *)mat2, (int *)result, ROWS, COLS);
printf("结果:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
3、使用动态内存分配实现矩阵加法
使用动态内存分配来创建矩阵,进行矩阵加法。
#include <stdio.h>
#include <stdlib.h>
void addMatrices(int **mat1, int **mat2, int **result, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
int main() {
int rows = 3, cols = 3;
int **mat1 = (int **)malloc(rows * sizeof(int *));
int **mat2 = (int **)malloc(rows * sizeof(int *));
int **result = (int **)malloc(rows * sizeof(int *));
for (int i = 0; i < rows; i++) {
mat1[i] = (int *)malloc(cols * sizeof(int));
mat2[i] = (int *)malloc(cols * sizeof(int));
result[i] = (int *)malloc(cols * sizeof(int));
}
// Initialize matrices
int init1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int init2[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mat1[i][j] = init1[i][j];
mat2[i][j] = init2[i][j];
}
}
addMatrices(mat1, mat2, result, rows, cols);
printf("结果:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
// Free allocated memory
for (int i = 0; i < rows; i++) {
free(mat1[i]);
free(mat2[i]);
free(result[i]);
}
free(mat1);
free(mat2);
free(result);
return 0;
}