# How to: Coding an ARRAY of UDT - STRUCTS

Hello
I´ve coded two structs:

``````struct ELEMENT {
unsigned long duration;
byte colour[3];
};
``````

containing the general data structure.

The following structs are used to built the needed sequences:

``````struct SEQUENCE4_1 {
ELEMENT element[2];
};
struct SEQUENCE4_2{
ELEMENT element[4];
};
struct SEQUENCE4_3 {
ELEMENT element[6];
};
``````

And the initialization of the datasets from oc1 to oc4:

``````SEQUENCE4_1  oc1{1000,{0,0,0,},1000,{0,0,0}};
SEQUENCE4_2  oc2{1000,{0,0,0,},1000,{0,0,0},1000,{0,0,0,},1000,{0,0,0}};
SEQUENCE4_3  oc3{1000,{0,0,0,},1000,{0,0,0},1000,{0,0,0,},1000,{0,0,0},1000,{0,0,0,},1000,{0,0,0}};
``````

How to build an ARRAY containing the information to have access to the specified UDT, oc1 to oc3, within a for-each-loop?

Many thanks for sharing know how.

Have a nice day and enjoy coding in C++.

Here is an example of an array of structs which, judging from the variable names, I wrote to illustrate the principle in the context of a truck racing sketch

``````const byte numberOfTrucks = 4;

struct trucks
{
unsigned long ignoreStart;
boolean currentlyIgnored = true;
int lapCount = 0;

} truckData[numberOfTrucks];

void setup()
{
Serial.begin(115200);
truckData[0].currentlyIgnored = true;
truckData[1].currentlyIgnored = false;
truckData[2].currentlyIgnored = false;
truckData[3].currentlyIgnored = true;
for (int truck = 0; truck < numberOfTrucks; truck++)
{
Serial.print(truck);
Serial.println(truckData[truck].currentlyIgnored ? " currently ignored" : " timing in progress");
}
}

void loop()
{
}``````

Note that like all arrays, the members of an array of structs must be identical

following output from code below

``````    1000 - 0, 0, 0
1001 - 0, 0, 0

2000 - 0, 0, 0
2001 - 0, 0, 0
2002 - 0, 0, 0
2003 - 0, 0, 0

3000 - 0, 0, 0
3001 - 0, 0, 0
3002 - 0, 0, 0
3003 - 0, 0, 0
3004 - 0, 0, 0
3005 - 0, 0, 0
``````
``````struct ELEMENT {
unsigned long duration;
byte colour[3];
};

ELEMENT seq1 [] = {
{ 1000, {0,0,0} },
{ 1001, {0,0,0} },
{ }
};

ELEMENT seq2 [] = {
{ 2000, {0,0,0} },
{ 2001, {0,0,0} },
{ 2002, {0,0,0} },
{ 2003, {0,0,0} },
{ }
};

ELEMENT seq3 [] = {
{ 3000, {0,0,0} },
{ 3001, {0,0,0} },
{ 3002, {0,0,0} },
{ 3003, {0,0,0} },
{ 3004, {0,0,0} },
{ 3005, {0,0,0} },
{}
};

char s [80];

// -----------------------------------------------------------------------------
void
dispElement (
ELEMENT  *p )
{
for ( ; p->duration; p++)  {
sprintf (s, "  %6ld - %d, %d, %d",
p->duration, p->colour [0], p->colour [1], p->colour [2] );
Serial.println (s);
}
Serial.println ();
}

// -----------------------------------------------------------------------------
void setup (void) {
Serial.begin (9600);

dispElement (seq1);
dispElement (seq2);
dispElement (seq3);
}

void loop (void) {
}
``````

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.