Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize an array from another array in C

Tags:

c

I would like to initialise an array with the value set in another array, like:

uint8_t array_1[] = {1, 2, 3};

uint8_t array_2[] = array_1;

Of course this would not work since array_1 is considered a pointer. What I'm trying to do is to be able to statically initialize array_2 with the value of array_1 without using memset.

Since array_1 and array_2 would in my case be constant global buffers, I believe there should be a way to do this, but I haven't figured out how, or by using defines, but I'd rather stick to the other solution if possible.

Thank you

like image 997
kokopelli Avatar asked Oct 31 '25 17:10

kokopelli


1 Answers

There is no particularly elegant way to do this at compile-time in C than using #define or repeating the initializer. The simplest versions:

uint8_t array_1[] = {1, 2, 3};
uint8_t array_2[] = {1, 2, 3};

or

#define INIT_LIST {1, 2, 3}

uint8_t array_1[] = INIT_LIST;
uint8_t array_2[] = INIT_LIST;

Though if you were using structs, you could do:

typedef struct
{
  int arr [3];
} array_t;

array_t array_1 = { .arr = {1,2,3} };
array_t array_2 = array_1;

But that only works if these are local objects and this is essentially equivalent to calling memcpy.

like image 88
Lundin Avatar answered Nov 02 '25 08:11

Lundin