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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With