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)
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
SpiderRico
  • 1,890
  • 8
  • 28
  • 48
  • 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](http://stackoverflow.com/a/823600/195488) –  May 08 '13 at 12:55

2 Answers2

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;
}
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • 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. – SpiderRico May 08 '13 at 13:21
  • @user2362377 Right, and with non-square matrices, the `*(m+i+j)` could also access out-of-bounds, so I fixed that too now. – Daniel Fischer May 08 '13 at 13:39
1
m = &a[0];
for ( j = 0; j < d1; j++ )
{
    for ( i = 0; i < d2; i++)
        cout << *m++;
    cout << endl;
}
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434