1

I'm making an 2D Game to train my class managment.

I have two multidimensional arrays: Map1 and Map. I want to replace Map values with Map1 ones. How can I do this without replacing every element manually like Map[0][0] = '#' etc.

char Map[10][21] = {
    "####################",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "####################"};

char Map1[10][21] = {
"####################",
"#                  #",
"#                  #",
"#                  #",
"#                  #",
"#       TEST       #",
"#                  #",
"#                  #",
"#                  #",
"####################"};
0

4 Answers 4

1

Since multi-dimensional arrays are guaranteed to be contiguous in memory layout, and the two arrays have the same size, you can do this:

std::copy((char*)Map1, (char*)Map1 + sizeof(Map1), (char*)Map);

Note that the cast is necessary to make the whole copy as a array of char.

On the other hand, this task would have been more straightforward if you used std::vector<std::string>, you could directly assign: Map = Map1...

Sign up to request clarification or add additional context in comments.

Comments

0

I personally would not write code like this, but for testing...

int main( )
{
    for( size_t i= 0; i < 10; ++i )
        std::cout << Map[ i ] << std::endl;

    memcpy( Map, Map1, sizeof( Map ) );

    for( size_t i= 0; i < 10; ++i )
        std::cout << Map[ i ] << std::endl;
}

Comments

0

Just leverage the built-in copy assignment for classes:

struct map {
    char Map[10][21];
};

map Map = { 
    "####################",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "####################"
};

map Map1 = {
    "####################",
    "#                  #",
    "#                  #",
    "#                  #",
    "#                  #",
    "#       TEST       #",
    "#                  #",
    "#                  #",
    "#                  #",
    "####################"
};

int main()
{
    Map = Map1;
}

Comments

0

Instead of copying them, maybe it is more successful to exchange its contents, this can be done using std::swap

swap(Map,Map1);

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.