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


   ptr1 = m; 
    ptr2 = m + (d2*(d1-1));

     if ( *ptr1 != *ptr2){  
       temp = ptr2;     
       ptr2 = ptr1;     
       ptr1 = temp;
    }
ptr1 +=d2;
ptr2 -= d2;

In order to do

From

4 1

3 7

5 2

To

5 2

3 7

4 1

This is what i've came up with so far which is pretty much nothing. I'm having problems with finding what kind of a loop would fit in.

3
  • why not declare an array of pointers and flip those? Commented May 10, 2013 at 16:05
  • It's been a while since I've done this, but shouldn't it be ptr1 = &m, ptr2 = &m + ((d2 * d1) - 1)? then you do += / -= (data type size * 2)? Commented May 10, 2013 at 16:09
  • 1
    You really should use std::swap(*ptr1, *ptr2). That makes it far clearer what you are trying to do. Commented May 10, 2013 at 23:01

3 Answers 3

2

Just reverse the whole thing and then reverse each row:

row/col representation:
4 1 => 2 5 => 5 2
5 2    1 4    4 1

actual layout of m:
4 1 5 2 => 2 5 1 4 => 5 2 4 1
Sign up to request clarification or add additional context in comments.

4 Comments

So first i take it's transpose.I guess i can do that.But then its comes up to same problem doesn't it just row instead of column ?
You've allocated a flat (1-dimensional) array, you can reverse that. Then you interpret that array as 2-dimensional with something like m[x + cols*y], so you can reverse each of those rows.
@user2362377: Flipping a row is essentially the same problem as flipping a column, except it is much faster because the stride is 1, you use cache better. Still, if you think in terms of exchanging two rows, instead of flipping a column, you will have a simpler and faster answer yet.
I've menaged to reverse my array but still having problems with the 2nd part.Some code would be helpfull.
0

You need two loops, one for the rows that you want to flip, and then to flip each element on that row. So int row runs from 0 to 2, and int column runs from 0 to 1, when flipping your 3x2 matrix.

Comments

0

Better ways have been described in the previous answers. So my answer will address why nothing changed in your output. You were swapping pointers not values. You want to do:

temp = *ptr2;     
*ptr2 = *ptr1;     
*ptr1 = temp;

--ptr2;
++ptr1;

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.