Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Values in array getting altered yet they shouldn't

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");

}

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’re declaring matrixes of size 2×2 and access them as if they were 3×3. What’s happening more precisely is a buffer overflow, you write somewhere you shouldn’t, and by doing so you overwrite other variables.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading