int main() {
int n = 0;
int matrix[n][n];
printf("Insert the order of the matrix:");
scanf("%d", &n);
for (int i = 0; i < n; i )
for (int j = 0; j < n; j )
matrix[i][j] = i j;
printf("The matrix is:\n");
for (int i = 0; i < n; i ) {
for (int j = 0; j < n; j ) {
printf("%d ", matrix[i][j]);
}
}
for a 2x2 matrix the output should be 0 1 1 2
, but it is 1 2 1 2
, and for a 3x3 matrix it should be 0 1 2 1 2 3 2 3 4
but it shows 2 3 4 2 3 4 2 3 4
The issue is that my output is always just my first row of the matrix, repeated n times. Any help?
CodePudding user response:
#include <stdio.h>
int main() {
int n = 0;
printf("Insert the order of the matrix:");
scanf("%d", &n);
int matrix[n][n];
for (int i = 0; i < n; i )
for (int j = 0; j < n; j )
matrix[i][j] = i j;
printf("The matrix is:\n");
for (int i = 0; i < n; i ) {
for (int j = 0; j < n; j ) {
printf("%d ", matrix[i][j]);
}
}
}
CodePudding user response:
You declare the array with size n
equal zero. Then the length of a row is zero, hence the offset for each consecutive row is zero, too. That means all rows are stored at the same place. As a final result, the last row's values overwrite all the previous rows.
Do input n
before declaring matrix[n][n]
.