0

I'm using Atmel Studio.

This is my struct:

struct button {
    char *button_port;
    uint8_t button_pin;
    uint8_t flagPress;
    uint8_t flagClick;
    uint8_t buttonCount;
    uint8_t time_button;
} button_left, button_right, button_menu;

I want to set initial button parameters. This is not working:

button_left.button_port = "PORTD";

I'm getting the error

Error expected '=', ',', ';', 'asm' or '__attribute__' before '.' token

However, this works:

struct button button_left = {"PORTD", 6, 0, 0, 0, 12};

How can I use the struct in more comfortable way like this:

button_left.button_port = "PORTD"
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • Welcome to StackOverflow! Please provide a [example] that tries to set `button_left.button_port` but triggers the error. – the busybee Sep 27 '20 at 19:13
  • 2
    Does this answer your question? [What does dot (.) mean in a struct initializer?](https://stackoverflow.com/questions/8047261/what-does-dot-mean-in-a-struct-initializer) – Siguza Sep 27 '20 at 19:13
  • As a side point, you should attach `const` modifier to the `button_port` field since you're assigning a string literal to it. – Daniel Walker Sep 27 '20 at 20:44

1 Answers1

0

Initializations of the struct looks a bit different that initializations of the scalars.

struct button 
{
    char *button_port;
    uint8_t button_pin;
    uint8_t flagPress;
    uint8_t flagClick;
    uint8_t buttonCount;
    uint8_t time_button;
};

struct button button_left = {"PORTA"};
struct button button_right = {.button_port = "PORTC"};

// these are called compound literals
struct button button_3 = (struct button){.button_port = "PORTC"};
struct button button_4 = (struct button){.button_port = "PORTC"};

You need to read about it in the C book. Do not learn C from examples or YouTube.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Ok, i got answer. Structures have to be initialized outside the functions only in this way: `struct button button_left = {"PORTD", 6, 0, 0, 0, 12};` This should be used only inside the function: `button_left.button_port = "PORTD";` – Taras Parashchuk Sep 27 '20 at 23:46