7

I want to copy 2d array and assign it to another.

In python i will do something like this

grid = [['a','b','c'],['d','e','f'],['g','h','i']]
grid_copy = grid

I want to do same in C.

char grid[3][3] = {{'a','b','c'},{'d','e','f'},{'g','h','i'}};

How do i copy this array to copy_grid ?

1
  • 3
    Note that your Python code does not copy the data. Both grid and grid_copy refer to the same list. Try changing an element in one and see what happens to the other. Commented Dec 16, 2012 at 16:57

3 Answers 3

12

Use memcpy standard function:

char grid[3][3] = {{'a','b','c'},{'d','e','f'},{'g','h','i'}};
char grid_copy[3][3];

memcpy(grid_copy, grid, sizeof grid_copy);
Sign up to request clarification or add additional context in comments.

1 Comment

how can i assign particular value like grid_copy[0][1] = grid[2][2]. I know this is wrong but i think you know what i mean to ask.
11

Use memcpy , don't forget to include <string.h>

#include <string.h>
void *memcpy(void *dest, const void *src, size_t n);

Or, do it manually using loop put each value one by one.

Comments

1

Although the answers are correct, one should remark that if the array is inside a structure, assigning structures will copy the array as well:

struct ArrStruct
{
    int arr[5][3];
};

int main(int argc, char argv[])
{
    struct ArrStruct as1 = 
    { { { 65, 77, 8 }, 
    { 23, -70, 764 }, 
    { 675, 517, 97 }, 
    { 9, 233, -244 }, 
    { 66, -32, 756 } } };

    struct ArrStruct as2 = as1;//as2.arr is initialized to the content of as1.arr

    return 0;
}

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.