Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign values of array to another array(making copy) in c?

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 ?

like image 771
Nakib Avatar asked Dec 16 '12 16:12

Nakib


2 Answers

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);
like image 196
ouah Avatar answered Sep 25 '22 19:09

ouah


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.

like image 41
Omkant Avatar answered Sep 22 '22 19:09

Omkant