1

I have a struct that contains a field that is an array of 7 cells and I want to define the values of the cells quickly and easily.

Is there a way to easily and quickly declare and define an array such as with this manner ?

struct my_struct
{
   uint8_t array[7];
}

struct my_struct var = {0};

memcpy(var.array, (uint8_t){0,1,2,3,4,5,6}, 7);

Or this way ?

struct my_struct
{
   uint8_t array[7];
}

struct my_struct var = {0};

var.array = (uint8_t)[]{0,1,2,3,4,5,6};

Or I must do this way ?

struct my_struct
{
   uint8_t array[7];
}

struct my_struct var = {0};

var.array[0] = 0;
var.array[1] = 1;
var.array[2] = 2;
var.array[3] = 3;
var.array[4] = 4;
var.array[5] = 5;
var.array[6] = 6;

Thank you ;)

Amaury
  • 73
  • 7

3 Answers3

2

Array and struct initializers can be nested:

struct my_struct var = { {0,1,2,3,4,5,6} };
dbush
  • 205,898
  • 23
  • 218
  • 273
1

Use a compound literal.

Your first attempt was close, but the type specification is missing the [] that make it an array type.

memcpy(var.array, (uint8_t[]){0,1,2,3,4,5,6}, 7);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks that's what I'm looking for ! Side question: When declaring an array this way. Where is stored (uint8_t[]){0,1,2,3,4,5,6}, in the stack or as a global variable ? – Amaury Jan 22 '21 at 16:28
  • 1
    From the [spec](http://port70.net/~nsz/c/c11/n1570.html#6.5.2.5): **If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.** – Barmar Jan 22 '21 at 16:33
1
var.array = (uint8_t)[]{0,1,2,3,4,5,6};

Do you mean a compound literal?

then the syntax is (uint8_t []) instead of (uint8_t)[]

But you can not assign to an array (Why are arrays not lvalues).

Your first example is almost correct:

memcpy(var.array, (uint8_t){0,1,2,3,4,5,6}, 7);

but again, use the correct syntax:

memcpy(var.array, (uint8_t []){0,1,2,3,4,5,6}, 7);
David Ranieri
  • 39,972
  • 7
  • 52
  • 94