Ruggero Latella Ruggero Latella - 17 days ago 5
C Question

C Matrix Sum Wrong! /edited/ /sorryforlastone/

I'm rewriting the last post i did with the screenshot since it wasnt readable. I'm sorry. This time i managed to copy and paste the code. The problem is if i insert for example:

1st Matrix
1 2 3
4 5 6
7 8 9

2nd Matrix
2 2 2
2 2 2
2 2 2


It gives me this Matrix sum output:

9 10 11
9 10 11
9 10 11


which is obviously wrong! I cant seem to find why so im asking you experts xD.
Thank you in advance for any help and again sorry for last post (I'm new to programming dynamics).

#include <stdlib.h>
#include <stdio.h>

int main(void)
{

int r,c;
int ir,ic;
int matrix1[r][c];
int matrix2[r][c];
int finalmatrix[r][c];

printf("Insert number of rows of the matrixes (max 10): ");
scanf("%d", &r);
printf("Insert number of columns of the matrixes (max 10): ");
scanf("%d", &c);


while(r!=c)
{
printf("The number of rows and columns are not equal, retry:\n");
printf("Insert number of rows of the Matrix (max 10): ");
scanf("%d", &r);
printf("Insert number of columns of the Matrix (max 10): ");
scanf("%d", &c);
}

for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
printf("Insert element row %d and column %d of the first matrix: ", ir, ic);
scanf("%d", &matrix1[ir][ic]);
}
}

for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
printf("Insert element row %d and column %d of the second matrix: ", ir, ic);
scanf("%d", &matrix2[ir][ic]);
}
}

for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
finalmatrix[ir][ic]=matrix1[ir][ic]+matrix2[ir][ic];
}
}

printf("The sum Matrix is:\n");

for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
printf("%d ", finalmatrix[ir][ic]);
}
printf("\n");
}

return 0;
}

Answer

Your code fails to initialize the variables r and c before declaring the VLAs with them. You have no way of knowing what size these arrays are, or if r and c are even positive values! I am surprised that this code will even run. I ran the code that you posted, and got this runtime error:

runtime error: variable length array bound evaluates to non-positive value -1208010352

I made the following change, and the code works:

int r,c;
int ir,ic;

printf("Insert number of rows of the matrixes (max 10):  ");
scanf("%d", &r);
printf("Insert number of columns of the matrixes (max 10):  ");
scanf("%d", &c);

int matrix1[r][c];
int matrix2[r][c];
int finalmatrix[r][c];

Output for your example:

The sum Matrix is:
3 4 5 
6 7 8 
9 10 11 

According to the standard (ISO/IEC 9899/1999 6.7.5.2) paragraphs 1 and 5:

the [ and ] may delimit an expression.... it shall have a value greater than zero.

So a negative value for r or c, which is very likely, results in undefined behavior, meaning that anything could happen! When I ran the code, I got a runtime error. You ran the same code, and got a different result. The behavior is undefined, so there is no telling what might happen.