Charlie RC
Charlie RC

Reputation: 219

Copying 1 dimension of a 2-dimensional array to another part of the same array

I am new to C++.

Given a 2-dimensional array defined as:

boolean myArray[3][8];

and I want to shuffle the cells around in the first dimension elements around so that, say, myArray[2][........] is copied to myArray[2][........].

I would normally iterate through the array with a nested loop that copies each cell. Is there a better way to do this? In other words, is there a way to copy a single dimension of a two dimensional array to another part of that that array with a single command of some sort?

Upvotes: 0

Views: 1057

Answers (2)

Dtor
Dtor

Reputation: 609

You can use:

memmove(&myArray[2], &myArray[2][2], 4);

To copy some of the bytes from the 2nd array to the beginning of itself.

Upvotes: 0

karlphillip
karlphillip

Reputation: 93468

In this example the program declares the following 2D int array (instead of bool):

3 5 7 9 11 13 15 17 
8 7 6 5 4 3 2 1 
2 4 6 8 10 12 14 16 

and demonstrates how to switch the data between the first and last indexes:

#include <stdio.h>
#include <string.h>

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

    // Copy data from index 2 to index 0
    int bkup[8] = { 0 };
    memcpy(bkup, myArray[0], sizeof(myArray[0]));
    memcpy(myArray[0], myArray[2], sizeof(myArray[2]));
    memcpy(myArray[2], bkup, sizeof(bkup));

    // Print array content to the screen
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 8; j++)
            printf("%d ", myArray[i][j]);
        printf("\n");
    }      

    return 0;
}

Output:

2 4 6 8 10 12 14 16 
8 7 6 5 4 3 2 1 
3 5 7 9 11 13 15 17 

Upvotes: 1

Related Questions