Home > OS >  Setting multiple array values after declaration
Setting multiple array values after declaration

Time:03-19

Is there any way to set the values in an array after it has been declared?

unsigned char values[16];
// Some other code to decide what to put into the values array
values = {0xAA,0xBB,0xCC,0xDD};

I saw this solution but it is for a C implementation. I'm trying to be efficient on memory and avoid a memcpy as well as I don't always need to fill the entire array like in the example above. So far this is the only method that I know works but its very kludgy.

unsigned char values[16];
// Some other code to decide what to put into the values array
values[0] = 0xAA;
values[1] = 0xBB;
values[2] = 0xCC;
values[3] = 0xDD;

CodePudding user response:

Maybe something like this would do:

unsigned char* values;
// Some other code to decide what to put into the values array
values = (unsigned char[]) {0xAA,0xBB,0xCC,0xDD};

Appendix: Note that it really depends on what you need. Since values is not an array anymore in this case.

CodePudding user response:

Either use memcpy or assign each index manually, there is no other sensible solution. You don't have to memcpy the whole array at once, just restrict it to some indices:

memcpy(&values[0], (unsigned char[]){0xAA,0xBB,0xCC,0xDD}, 4);

where values[0] can easily be changed to any values[i]. This is also safe as far as alignment is concerned. Note that there should be no benefit in terms of efficiency between this code and assigning all 4 indices manually. Strive to make the code as readable as possible - if you think compound literals are hard to read for example, then stick to what you already have.

  • Related