Home > Enterprise >  C Weird behavior while giving a value to the the predecessor element of a matrix column (v[i][j-1]
C Weird behavior while giving a value to the the predecessor element of a matrix column (v[i][j-1]

Time:04-12

So I was trying to make a matrix where the elements of the main diagonal would increase by 3 one by one and I also wanted to change the values of the previous and the next element of the the main diagonal with their predecessor and succesor. Something like this:

It all worked fine until the predecessor element. For some reason v[i][j-1] doesn't work?

I would like to mention I am a beginner.

Here is the code:

#include <iostream>
using namespace std;

int n, v[22][22];

int main()
{
    cin >> n;
    int k = 1;
    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < n; j  )
        {
            if (i == j)
            {
                v[i][j] = k;
                v[i][j   1] = k   1;
                v[i][j - 1] = k - 1; //this is the part where it doesn't work
            }
            cout << v[i][j] << " ";
        }
        k  = 3;
        cout << "\n";
    }
}

Here is the result I am getting

Edit: I also tried it when i and j start from 1, so there won't be any negative index value. It still doesn't work.

CodePudding user response:

For starters there is no need to use nested for loops. It is enough to use only one for loop.

When i is equal to 0 and j is equal to 0 then this expression v[i][j - 1] access memory outside the array that invokes undefined behavior.

The same problem exists when n is equal to 22 for the expression and i and j are equal to n - 1 for this v[i][j 1] .

You should check these situations.

Also try to declare variables in minimum scope where they are used. For example there is no need to declare the array in the global namespace.

Here is shown how you can organize the loops.

    int value = 1;

    for (size_t i = 0; i < n; i  )
    {
        v[i][i] = value;
        if (i != 0) v[i][i - 1] = value - 1;
        if (i != n - 1) v[i][i   1] = value   1;

        value  = 3;
    }

    for (const auto &row : v)
    {
        for (const auto &item : row)
        {
            std::cout << std::setw( 3 ) << item << ' ';
        }
        std::cout << '\n';
    }

For example if n is equal to 5 then the output will be

  1   2   0   0   0
  3   4   5   0   0
  0   6   7   8   0
  0   0   9  10  11
  0   0   0  12  13
  • Related