user2861018
user2861018

Reputation: 1

Problems creating matrices from user input in C++

I'm trying to just make a simple program where the user inputs every value of a matrix, then the program prints the matrix. So far I have

#include <iostream>

using namespace std;
int main()
{
    int n;
    cout << "A is an nxn matrix.\nn=";
    cin >> n;
    int matrix[n-1][n-1];
    for (int i=0;i<n;i++)
    {
        for (int j=0;j<n;j++)
        {
            cout << "A[" << i+1 << "][" << j+1 << "]=";
            cin >> matrix[i][j];
        }
    }
    cout << "[[ ";
    for (int i=0;i<n;i++)
    {
        for (int j=0;j<n;j++)
        {
            cout << matrix[i][j] << " ";
        }
        if (i!=n-1) //Just to make the output pretty
            cout << "]\n [ ";
        else
            cout << "]]";
    }
}

`

However, whenever I put in a matrix of any size, for instance [[1,2,3][4,5,6][7,8,9]], the program returns [[1,2,4][4,5,7][7,8,9]].

Can anyone tell me why this is happening and how to fix it?

Upvotes: 0

Views: 4659

Answers (2)

Maxim Razin
Maxim Razin

Reputation: 9466

Should be int matrix[n][n]. Generally, an array A[n] has indexes from 0 to n-1.

You are overflowing the boundaries of the row, for example, if you have int matrix[2][2] and set matrix[0][2] = 42, you are actually assigning matrix[1][0], and when you set matrix[2][0] you are writing beyond the array boundaries potentially destroying some other variables or even call stack, which may cause undefined behavior.

Upvotes: 0

P0W
P0W

Reputation: 47794

You're getting an undefined behavior for accessing out of range in matrix[i][j] when i or j equals n-1 for your matrix declared as matrix[n-1][n-1]

Use:

int matrix[n][n]; // will say 0 to n-1

instead of

int matrix[n-1][n-1];

Upvotes: 2

Related Questions