0

I'm having some difficulty assigning a value to a variable in a struct array outside the loop and setup functions. Assigning a value to an int or char array works completely fine but this doesn't.

The example code and error message returned after trying to compile are below. Any help is greatly appriciated. Thanks

void setup()
{
}

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
} trap_game_details[2];

trap_game_details[0].random_min = 1;

void loop()
{

}

src/sketch.ino:13:5: error: ‘trap_game_details’ does not name a type trap_game_details[0].random_min = 1; ^ .build/uno/Makefile:166: recipe for target '.build/uno/src/sketch.o' failed

2 Answers 2

1

Assigning a value to an int or char array works completely fine but this doesn't.

It only works fine if you do it on the declaration.

eg.

This works:

int foo = 42;  < ---- declare and define with initial value

This doesn't:

int foo;   // < ---- declare and define

foo = 42;  // < ---- assignment statement

Your code was like the second example.


Majenko has shown one way. He split the declaration into two parts. The first part declared the type trap_game_detail, and the second part is an instance of that type, like this:

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

Alternatively, and a bit closer to what you were doing, just keep going with the initialization values after you define the structure, like this:

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
} trap_game_details[2] =  
  {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
  }; 
1
  • Ah I see. Thanks very much for the explanation Nick, that was really helpful.
    – oduffy
    Sep 3, 2015 at 9:57
1

You can't access array contents in the global scope like that. You have to assign the entire block of data in one go:

struct trap_game_detail {
    byte flush_quantity;
    byte flush_interval;
    byte random_min;
    byte random_max;
    byte random_quantity;
};

struct trap_game_details trap_game_details[2] = {
    { 10, 5, 1, 100, 4 },
    { 8, 23, 5, 95, 8 }
};

Items in the global scope aren't executed - only things in functions are executed. Accessing individual parts of an array or struct like you are trying to is a programatic operation, so can't be executed since it's not in a function.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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