newDev2000
newDev2000

Reputation: 311

shift cyclically second row in 2D array c++ 98

Hi guys i was looking around some old threads but i can't find anything that works for me. I need to shift second row in my array with cpp 98 from this

int mat[4][4] = {{1, 2, 3, 4}, 
                 {5, 6, 7, 8}, 
                 {9, 10, 11, 12}, 
                 {13, 14, 15, 16}};

to this

int mat[4][4] = {{1, 2, 3, 4}, 
                 {5, 6, 7, 8}, 
                 {12, 9 , 10, 11}, 
                 {13, 14, 15, 16}};

I don't want to print out anything just switching places in array, Thank you

Upvotes: 0

Views: 28

Answers (1)

D-RAJ
D-RAJ

Reputation: 3372

One very easy method is this, first create a temporary array to store the initial values,

int temp[4] = { mat[2][3], mat[2][0], mat[2][1], mat[2][2] };

Then use std::memcpy to copy the data into mat[2],

std::memcpy(mat[2], temp, sizeof(int) * 4);

Bonus: You can use a scope to save some memory. It would be like this,

int mat[4][4] = { {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12},
    {13, 14, 15, 16} };

...

{
    int temp[4] = { mat[2][3], mat[2][0], mat[2][1], mat[2][2] };
    std::memcpy(mat[2], temp, sizeof(int) * 4);
}

Upvotes: 2

Related Questions