Cpp Programmer
Cpp Programmer

Reputation: 126

Error in Multidimensional array code in C++

I've been revising on my coding skills recently and then I made a program that outputs the contents of a multidimensional array. It is simple but when I experimented with the code this is what that happened:

int dv[3][3] {
    {1,2,3},
    {4,5,6},
    {7,8,9}
};
for (auto col = dv; col != dv + 3; ++col) {
    for (auto row = *dv; row != *col + 3; ++row) {
        cout << *row << " ";
    }
}

Output:

1 2 3 1 2 3 4 5 6 1 2 3 4 5 6 7 8 9

Can anybody please tell me why is this happening?

Upvotes: 0

Views: 51

Answers (2)

Telokis
Telokis

Reputation: 3389

Why does my code outputs so ?

Your error is inside the second loop initialization : auto row = *dv;. By doing so, you systematically come back to the beginning. Then, you go to *col + 3. Look at it this way :

First loop turn :

col = dv;
row = *dv;

Prints each number until row == *col + 3

Output : 1 2 3

Second loop turn :

col = dv + 3;
row = *dv;

Prints each number until row == *col + 3 but col is dv + 3

Output : 1 2 3 4 5 6 --> It started from the beginning (dv)

Total output with turn 1 and 2 : 1 2 3 1 2 3 4 5 6

Try this instead :

for (auto col = dv; col != dv + 3; ++col) {
    for (auto row = *col; row != *col + 3; ++row) { // (1)
        cout << *row << " ";
    }
}

// (1) : Starting at current `column` then printing until `column + 3`

Live example : https://ideone.com/Y0MKrW

Upvotes: 2

sfjac
sfjac

Reputation: 7304

Your inner loop is starting at *dv. That is probably not what you meant to do.

Upvotes: 0

Related Questions