kokopelli
kokopelli

Reputation: 262

initialize an array from another array in 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

Upvotes: 3

Views: 2574

Answers (2)

Lundin
Lundin

Reputation: 213458

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.

Upvotes: 7

codingwith3dv
codingwith3dv

Reputation: 369

You can do it like this

uint8_t length = sizeof(array_1) / sizeof(array_1[0]);
for(uint8_t i = 0; i < length; i++) {
  array_2[i] = array_2[i]
}

Upvotes: -3

Related Questions