TGrossb - 1 year ago 92
C++ Question

# Incorrect output of matrix in C++

I am writing a code to take a value and create a matrix with a size that allows for a pyramid of 1s to be made so the top one is at the x-1 element. For example, if the input was five, the output would be:

``````0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1
``````

The problem is the code is generating values that shouldn't be one, or it is not outputting the matrix the correct way. I have tried adding a cout to the code where it defines some values as 1 and those are correct, so I believe that the problem is in the output. For example, an input of x will give

``````0 0 0 0 1 0 0 0 1
0 0 0 1 0 1 0 1 0
1 0 1 0 0 0 1 0 0
0 1 0 0 0 1 0 1 0
1 0 1 0 0 0 0 0 1
``````

The code is as follows:

``````#include <iostream>
using namespace std;

int main() {
cout << "Matrix size:";
int x;
cin >> x;
int arr1[2*x][x];
for (int initialX=0; initialX<x; initialX++){
for (int initialY=0; initialY<=((2*x)-2); initialY++){
arr1[initialX][initialY]=0;
}
}
for (int set=0; set<x; set++){
arr1[set][x-1-set]=1;
arr1[set][x-1+set]=1;
}
for (int outX=0; outX<x; outX++){
for (int outY=0; outY<(2*x-1); outY++){
cout << arr1[outX][outY] << " ";
}
cout << endl;
}
return 0;
}
``````

This is my first time working with matrices in c++, so any help concerning matrices is appreciated. Also, if it's of any importance I'm using c++11. Thank you in advance.

The array dimensions need to be switched. Instead of

``````int arr1[2*x][x];
``````

use

``````int arr1[x][2*x];
``````

Because of that error, you are accessing the array out of bounds, which leads to undefined behavior.

Since VLAs are not standards C++, I highly recommend use of `std::vector`.

``````std::vector<std::vector<int>> arr1(x, std::vector<int>(2*x));
``````

That will also initialize all the elements to `0` and obviate the need to write explicit code to initialize the array elements to `0`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download