It's a program that requires the user to enter the values of two 3 by 3 matrix then finds the sum of both matrices and prints out the same together with the added matrices but for some reason after entering the values of both matrices the a value in matrix gets altered then it affects the sum but at times it doesn't
#include<stdio.h>
void main(){
int matrix1[2][2];
int matrix2[2][2];
int sumMatrix[2][2];
for(int i = 0; i<3; i ){
for(int j = 0; j<3; j ){
printf("Matrix[%d][%d]\n", i, j);
printf("Enter matrix one's values> ");
scanf("%d", &matrix1[i][j]);
}
printf("\n");
}
for(int i = 0; i<3; i ){
for(int j = 0; j<3; j ){
printf("Matrix[%d][%d]\n", i, j);
printf("Enter matrix two's values> ");
scanf("%d", &matrix2[i][j]);
}
printf("\n");
}
for(int i = 0; i<3; i ){
for(int j = 0; j<3; j ){
sumMatrix[i][j] = matrix1[i][j] matrix2[i][j];
}
}
for(int i = 0; i<3; i ){
for(int j = 0; j<3; j ){
printf("%d ", matrix1[i][j]);
}
printf("\n");}
printf("\n");
for(int i = 0; i<3; i ){
for(int j = 0; j<3; j ){
printf("%d ", matrix2[i][j]);
}
printf("\n");}
printf("\n");
for(int i = 0; i<3; i ){
for(int j = 0; j<3; j ){
printf("%d ", sumMatrix[i][j]);
}
printf("\n");
}
}
CodePudding user response:
You're declaring matrixes of size 2x2 and access them as if they were 3x3. What's happening more precisely is a buffer overflow, you write somewhere you shouldn't, and by doing so you overwrite other variables.
CodePudding user response:
Ok so clearly I'm the idiot. I thought array sizes are set based on the number of indices they'll have, so instead of int matrix1[2][2]
it should be int matrix [3][3]
CodePudding user response:
Lad, that is array overflow.
int matrix1[2][2];
But in the loop, you may get matrix1[2][1], matrix1[2][2].