Inicializando matriz de estructuras

Dec 20 2020

Me definí una estructura:

typedef struct {
  unsigned char current;
  unsigned char start;
  unsigned char target;
  unsigned long startTime;
  unsigned int duration;
} led;

Pude inicializar una instancia de eso como esta:

led h_red = {0,0,255,0,300};

Sin embargo, cuando trato de tenerlos en una matriz:

led leds[LEDS];
leds[0] = {0,0,0,0,0};
leds[1] = {0,0,0,0,0};
leds[2] = {0,0,255,0,300};

Me sale este error

signal:28:1: error: 'leds' does not name a type
 leds[0] = {0,0,0,0,0};
 ^~~~
signal:29:1: error: 'leds' does not name a type
 leds[1] = {0,0,0,0,0};
 ^~~~
signal:30:1: error: 'leds' does not name a type
 leds[2] = {0,0,255,0,300};
 ^~~~

Y no tengo idea de lo que estoy haciendo mal aquí. Puedes ver el cambio completo aquí en GitHub

Respuestas

8 EdgarBonet Dec 20 2020 at 21:17
led h_red = {0,0,255,0,300};

Aquí, está definiendo una variable y, al mismo tiempo, le está dando un valor inicial. A esto se le llama inicialización .

led leds[LEDS];

Aquí está definiendo una matriz. Dado que está en el ámbito global y no se inicializa explícitamente, se inicializa implícitamente en todos los bytes cero.

leds[0] = {0,0,0,0,0};

Aquí, está intentando dar un valor a un elemento de la matriz que ya se ha definido previamente. Por tanto, no se trata de una inicialización, sino de una asignación . A diferencia de las inicializaciones, las asignaciones no pueden existir fuera de una función. Si desea asignar valores iniciales, puede hacerlo en setup().

Alternativamente, puede inicializar la matriz mientras la define:

led leds[LEDS] = {
    {0, 0,   0, 0,   0},
    {0, 0,   0, 0,   0},
    {0, 0, 255, 0, 300}
};
GabrielStaples Dec 23 2020 at 04:18

He votado a favor de la respuesta de @Edgar Bonet , porque es correcta.

Sin embargo, quiero agregar algunos ejemplos y explicaciones más.

Resumen clave:

En C y C ++, NO puede tener lógica de código fuera de las funciones. El contexto global fuera de las funciones está destinado a declaraciones , definiciones y algunas inicializaciones / constructores únicamente. Toda la lógica del código debe estar dentro de una función . La lógica del código incluye asignaciones de variables posteriores a la construcción, ifdeclaraciones, etc.

Ejemplos:

1. NO permitido:

Por lo tanto, NO puede hacer lo siguiente, ya que intenta realizar asignaciones que no se inicializan fuera de todos los ámbitos de función.

Tenga en cuenta también que en C ++ (que es Arduino), tampoco necesita usar typedefpara estructuras, así que lo eliminé de la structdefinición. También estoy usando los tipos stdint.h , que se consideran más seguros y "mejores prácticas" para los tipos de datos, ya que especifican el tamaño exacto del tipo en bits. Úselo uint8_ten lugar de unsigned char, en uint32_tlugar de Arduino Uno unsigned long, y en uint16_tlugar de Arduino Uno unsigned int. Además, en C ++ en particular, constexprse prefieren las enumeraciones #definea las constantes variables.

constexpr uint8_t NUM_LEDS = 3;

struct Led {
  uint8_t current;
  uint8_t start;
  uint8_t target;
  uint32_t startTime;
  uint16_t duration;
};

Led leds[NUM_LEDS];
// NOT OK: Variable (re)assignments are NOT allowed outside of functions in 
// C and C++.
leds[0] = {0, 0,   0, 0,   0};
leds[1] = {0, 0,   0, 0,   0};
leds[2] = {0, 0, 255, 0, 300};

void setup()
{
}

void loop()
{
}

2. SE permite:

Sin embargo, PUEDE tener inicializaciones de variables fuera de las funciones, siempre que ocurran al mismo tiempo que la construcción , por lo que esto es perfectamente válido:

Led leds[NUM_LEDS];
// This form of aggregate initialization during construction is just fine in the 
// global scope outside of all functions. 
Led leds[NUM_LEDS] = {
    {0, 0,   0, 0,   0},
    {0, 0,   0, 0,   0},
    {0, 0, 255, 0, 300},
};

void setup()
{
}

void loop()
{
}

3. También está permitido:

O bien, puede mover sus reasignaciones a una función, como setup():

Led leds[NUM_LEDS];

void setup()
{
    // This variable (re)assignment is just fine since it's inside 
    // of a function.
    leds[0] = {0, 0,   0, 0,   0};
    leds[1] = {0, 0,   0, 0,   0};
    leds[2] = {0, 0, 255, 0, 300};
}

void loop()
{
}

4. Ejemplo completo y ejecutable en una PC:

Aquí hay un ejemplo completo y ejecutable en una PC, con impresión para verificar que se cambió el contenido de la estructura:

Ejecútelo en línea usted mismo: https://onlinegdb.com/MnEOQgCQT.

#include <stdint.h>
#include <stdio.h>

// Get the number of elements in a C-style array 
#define ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))

constexpr uint8_t NUM_LEDS = 3;

struct Led {
  uint8_t current;
  uint8_t start;
  uint8_t target;
  uint32_t startTime;
  uint16_t duration;
};

// To initialize once at construction. This form of aggregate initialization 
// can be used anywhere: both inside and outside functions. 
Led leds[NUM_LEDS] = {
    { 1,  2,  3,  4,  5},
    { 6,  7,  8,  9, 10},
    {11, 12, 13, 14, 15},
};

// Print the full contents of an array of `Led` structs
void printLeds(const Led ledArrayIn[], size_t ledArrayLen)
{
    for (size_t i = 0; i < ledArrayLen; i++)
    {
        printf("ledArrayIn[%lu]\n"
               "current   = %u\n"
               "start     = %u\n"
               "target    = %u\n"
               "startTime = %u\n" 
               "duration  = %u\n\n",
               i,
               ledArrayIn[i].current,
               ledArrayIn[i].start,
               ledArrayIn[i].target,
               ledArrayIn[i].startTime,
               ledArrayIn[i].duration);
    }
}

int main()
{
    printf("Hello World\n\n");

    printLeds(leds, ARRAY_LEN(leds));
    
    printf("==============\n\n");
    
    // Do this to set or change the structs at any time AFTER construction!
    // This variable (re)assignment is only allowed inside of a function, NOT 
    // in the global scope outside of all functions!
    leds[0] = {10, 20,  30,  40,  50};
    leds[1] = {60, 70,  80,  90, 100};
    leds[2] = { 0,  0, 255,   0, 300};
    
    printLeds(leds, ARRAY_LEN(leds));

    return 0;
}

Salida de muestra:

Hello World

ledArrayIn[0]
current   = 1
start     = 2
target    = 3
startTime = 4
duration  = 5

ledArrayIn[1]
current   = 6
start     = 7
target    = 8
startTime = 9
duration  = 10

ledArrayIn[2]
current   = 11
start     = 12
target    = 13
startTime = 14
duration  = 15

==============

ledArrayIn[0]
current   = 10
start     = 20
target    = 30
startTime = 40
duration  = 50

ledArrayIn[1]
current   = 60
start     = 70
target    = 80
startTime = 90
duration  = 100

ledArrayIn[2]
current   = 0
start     = 0
target    = 255
startTime = 0
duration  = 300

Otras referencias:

  1. https://en.cppreference.com/w/cpp/language/aggregate_initialization
  2. [mi respuesta] https://stackoverflow.com/questions/61240589/how-to-initialize-a-struct-to-0-in-c/61240590#61240590