1

I'm trying to initialize a char array which is part of a structure as follows:

#define TRUE 1
#define FALSE 0

struct s_field_def { // structure for managing display field
  char f_txt[16]; // option text
  bool f_inhibit; // set this to inhibit updating of the field on the display
};

enum field_name {F_STATE, F_PULSE};

void setup() {

  // initialize display fields structure
  struct s_field_def fields[2]; // initialize the display fields
  fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
  fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running   
}

void loop() {

}

The initialization of the structure is producing an error at these lines:

  fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
  fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running   

no match for 'operator=' (operand types are 's_field_def' and '<brace-enclosed initializer list>')

What am I doing wrong here?

5

As explained in Michel Keijzers' answer, you cannot use the = operator to assign something to a string (a character array). However, you can initialize a string using =. There is an important distinction between assignment, which you can do anywhere in a program, an initialization, which can only be done at the time you define a variable.

For example:

int i = 2;  // initialization

void setup() {
    i = 4;  // assignment
}

In your specific case, you can initialize fields as follows:

struct s_field_def fields[2] = {
    {"HALTED", FALSE},  // displays the current run state
    {"@", TRUE}         // displays indicator of system running   
};
3
  • That reduces code size too, both in LOC and memory. And it's clearer: declaration and initialization is just one place. Maybe you can even declare data static. – user31481 Feb 7 '18 at 16:21
  • Thanks for the quick feedback about the distinction between assignment and initialization. That makes it clear. Problem solved! – whalphen K8VFO Feb 7 '18 at 16:31
  • I worked too long in an environment where this was not used. Upvoted for learning something. – Michel Keijzers Feb 7 '18 at 17:09
0

You can use this (but look at the accepted answer, it shows a much neater way).

  strcpy(fields[F_STATE].f_txt, "HALTED");
  fields[F_STATE].f_inhibit = FALSE;

  strcpy(fields[F_PULSE].f_txt, "@");
  fields[F_PULSE].f_inhibit = TRUE;

I don't have a compiler so I hope it's correct.

When using C++ you can use a constructor or assignment operator, but C does not have these object oriented features.

1
  • I was hoping to avoid strcpy for the initialization. – whalphen K8VFO Feb 7 '18 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.