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 ?

Omkant
  • 9,018
  • 8
  • 39
  • 59
Nakib
  • 4,593
  • 7
  • 23
  • 45
  • 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. – NPE Dec 16 '12 at 16:57

3 Answers3

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);
ouah
  • 142,963
  • 15
  • 272
  • 331
  • 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. – Nakib Dec 16 '12 at 17:06
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.

Omkant
  • 9,018
  • 8
  • 39
  • 59
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;
}
Andrey Pro
  • 501
  • 1
  • 10
  • 22