2
for ( j = 0; j < d1; j++ ){

    m += j;
        for ( i = 0; i < d1*d2; i +=d2){
        cout << *(m+i);
        }
    cout << endl;
}

d1,d2 are array dimensions

and

int* m = new int [d1*d2];

I want to traverse over my array and simply group and print the columns.Can't figure what's wrong with this code.Seems to be working fine untill the 3rd iteration in the following example:

Let's say my input values are 1 2 3 4 5 6 7 8 9

I get:

1 4 7

2 5 8

4 7 (something random)
1
  • 1
    You are going out of bounds on your array. If you are using C++, use a multi-dimensional vector instead. Multi-dimensional vector - How To Commented May 8, 2013 at 12:55

2 Answers 2

4

In

m += j;

you are first incrementing m by 0, then by one, then by 2. If we originally took a copy

int *start = m;

then in the first iteration of the outer loop, we'd have

m == start

in the second,

m == start + 1

in the third

m == start + 3

You'd want m == start + 2 there. Except that you want to keep m in order to delete it at the end, so you shouldn't change m at all but use something like

for ( j = 0; j < d2; j++ ){

        for ( i = j; i < d1*d2; i +=d2){
        cout << *(m+i);
        }
    cout << endl;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just a small mistake i guess:First iteration has to be j < d2 i guess.Else it disfunctions when row number is smaller than column number.
@user2362377 Right, and with non-square matrices, the *(m+i+j) could also access out-of-bounds, so I fixed that too now.
1
m = &a[0];
for ( j = 0; j < d1; j++ )
{
    for ( i = 0; i < d2; i++)
        cout << *m++;
    cout << endl;
}

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.