Inicializando Array de structs
Eu me defini como uma estrutura:
typedef struct {
unsigned char current;
unsigned char start;
unsigned char target;
unsigned long startTime;
unsigned int duration;
} led;
Consegui inicializar uma instância assim:
led h_red = {0,0,255,0,300};
No entanto, quando tento colocá-los em uma 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};
Eu recebo este erro
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};
^~~~
E não tenho ideia do que estou fazendo de errado aqui. Você pode ver a mudança completa aqui no GitHub
Respostas
led h_red = {0,0,255,0,300};
Aqui, você está definindo uma variável e ao mesmo tempo dando a ela um valor inicial. Isso é chamado de inicialização .
led leds[LEDS];
Aqui você está definindo um array. Como está no escopo global e não foi inicializado explicitamente, ele foi inicializado implicitamente com todos os bytes zero.
leds[0] = {0,0,0,0,0};
Aqui, você está tentando atribuir um valor a um elemento do array que já foi definido anteriormente. Portanto, esta não é uma inicialização, mas uma atribuição . Ao contrário das inicializações, as atribuições não podem existir fora de uma função. Se você quiser atribuir valores iniciais, pode fazê-lo em setup()
.
Como alternativa, você pode inicializar o array enquanto o define:
led leds[LEDS] = {
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 255, 0, 300}
};
Votei positivamente na resposta de @Edgar Bonet , porque ela está correta.
Quero adicionar mais alguns exemplos e explicações.
Resumo chave:
Em C e C ++, você NÃO pode ter lógica de código fora das funções. O contexto global fora das funções é destinado a declarações , definições e algumas inicializações / construtores apenas. Toda a lógica do código deve estar dentro de uma função . A lógica do código inclui atribuições de variáveis pós-construção, if
instruções, etc.
Exemplos:
1. NÃO permitido:
Portanto, você NÃO pode fazer o seguinte, uma vez que ele tenta fazer atribuições de não inicialização fora de todos os escopos de função.
Observe também que em C ++ (que é o Arduino), você também não precisa usar typedef
para structs, então removi isso da struct
definição. Também estou usando os tipos stdint.h , que são considerados mais seguros e "melhores práticas" para tipos de dados, pois especificam o tamanho exato do tipo em bits. Use uint8_t
no lugar de unsigned char
, em uint32_t
vez do Arduino Uno unsigned long
, e em uint16_t
vez do Arduino Uno unsigned int
. Além disso, em C ++ em particular, constexprou enums são preferidos #define
para definir constantes variáveis.
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. É permitido:
Você PODE, no entanto, ter inicializações de variáveis fora das funções, desde que ocorram ao mesmo tempo que a construção , então isso é perfeitamente 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. Também é permitido:
Ou você pode simplesmente mover suas reatribuições para uma função, 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. Exemplo completo executável em um PC:
Aqui está um exemplo completo executável em um PC, com impressão para verificar se o conteúdo da estrutura foi alterado:
Execute você mesmo online: 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;
}
Saída de amostra:
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
Outras referências:
- https://en.cppreference.com/w/cpp/language/aggregate_initialization
- [minha resposta] https://stackoverflow.com/questions/61240589/how-to-initialize-a-struct-to-0-in-c/61240590#61240590