#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void matrixRandomFill(int size, int size2, int matrix[size][size2]) {
srand(time(NULL));
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrix[i][j] = rand() % 9;
}
}
}
void matrixSum(int size, int size2, int matrix1[size][size2], int matrix2[size] [size2], int matrixSum[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrixSum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}
void matrixSubstract(int size, int size2, int matrix1[size][size2], int matrix2[size] [size2], int matrixSubstract[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrixSubstract[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
void matrixMultiply(int size, int size2, int matrix1[size][size2], int matrix2[size] [size2], int matrixMultiply[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
matrixMultiply[i][j] = matrix1[i][j] * matrix2[i][j];
}
}
}
void matrixPrint(int size, int size2, int matrix[size][size2]) {
for ( int i = 0; i < size; i++ ) {
for ( int j = 0; j < size2; j++ ) {
printf("%2d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int size;
printf("Enter matrix size NxN: ");
scanf("%d", &size);
int matrix1[size][size];
int matrix2[size][size];
int matrixSum[size][size];
int matrixSubstract[size][size];
int matrixMultiply[size][size];
matrixRandomFill(size, size, matrix1);
matrixRandomFill(size, size, matrix2);
printf("Printing first matrix:\n");
matrixPrint(size, size, matrix1);
printf("--------------------------------------\n");
printf("Printing second matrix:\n");
matrixPrint(size, size, matrix2);
printf("--------------------------------------\n");
printf("Printing matrix1 + matrix2:\n");
matrixPrint(size, size, matrixSum);
printf("--------------------------------------\n");
printf("Printing matrix1 - matrix2:\n");
matrixPrint(size, size, matrixSubstract);
printf("--------------------------------------\n");
printf("Printing matrix1 * matrix2:\n");
matrixPrint(size, size, matrixMultiply);
printf("--------------------------------------\n");
return 0;
}
功能看起来很正常,但我不断得到这样的东西:打印矩阵1 +矩阵2:0 0 0 0 0 0 0 0 0
或者
打印矩阵1-矩阵2:-1761243347 32767 -1761341440 32767 0 0 0 0 0
看起来像是某种分段错误,但我不知道我在哪里犯了错误。