0

I want to replace rows with columns in 2D array, but that doesn't work. The numbers are different in each of the two arrays.
And also in the second array, on second row, and fourth column there is always this same number (4253936).

How can i write it, so i can replace these rows and columns, without any number getting lost? I'm new to c++, So if you can explain it i would be thankfull.

    srand(time(NULL));

    int tab1[5][4];

    // Storing random numbers in array

    for(int i = 0;i<5;i++){
        for(int j = 0;j<4;j++){
            tab1[i][j] = rand()%18-9;
            cout<<tab1[i][j]<<' ';
        }
        cout<<endl;
    };
    

    int newtab[4][5];
    for(int i = 0; i < 4;i++){
        for(int j = 0;j<5;j++){
            newtab[i][j] = tab1[j][i];  
            cout<<newtab[j][i]<<' ';
        }
        cout<<endl;
    }
2
  • Of course the numbers print different. One of them is by rows and the other is by columns. The code seems to transpose your array ok. Commented Oct 7, 2020 at 20:11
  • You're assigning newtab[i][j] and printing newtab[j][i]. I suspect the weird number is an uninitalized value Commented Oct 7, 2020 at 20:12

1 Answer 1

1

The methodology you describe is called Transpose, which your code appears to implement.


The "weird" number that you see was because your code was invoking Undefined Behavior (UB), by having one of its indices goes out of array bounds, thus printing a garbage value.

The index that was going out of bounds was j in your print statement, since you wrongly used it to index the row of newtab 2D array, which is of size 4x5, meaning 4 rows. However j, which is meant to index the columns of newtab, goes from 0 to 4, so when j is equal to 4 you are effectively doing:

cout << newtab[4][0] << ' ';

which is out of bounds, since your matrix was defined like int newtab[4][5];.

Today that garbage value is 4253936, tomorrow it might be different. In your computer it was that, in mine it may be not -> Undefined Behavior!

To fix this, change:

cout << newtab[j][i] << ' ';

to:

cout << newtab[i][j] << ' ';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.