Say we want to try recreating Pokémon Red/Blue. What kinds of variables/data would we use to store information about our Pokémon? We could try something like the following:
//Different pieces of data about the pokemon in our party
int partySpecies[6];
int partyLevels[6];
int partyHP[6];
int partyAttack[6];
.
.
.But this would get annoying pretty quickly. We have language features that allow us to create groupings of the same type (arrays), but we haven’t yet explored ways to create groupings of different types of data.
Enter… structures! (we call them structs)
Structures are a language feature that allows us to group different types of data together, into a single aggregate data type. We sometimes refer to structs as user defined types.
So, what do they look like?
//Create a new struct
typedef struct
{
int species;
int level;
int hp;
int attack;
}Pokemon;
Now we have our own struct, which represents a Pokémon! And we can create different Pokémon just as we would create integers, floats, or any other type. Think of the struct definition above as a sort of… template, for creating new Pokémon in the future.
Pokemon myAmpharos;
myAmpharos.species = 181;
myAmpharos.level = 100;
Pokemon myUmbreon;
myUmbreon.species = 197;
myUmbreon.level = 60;The syntax above is how we would access the individual members of our Pokemon variables. Similar to how arrays use array syntax to access individual elements in an array, structs use the dot operator to access individual fields by name.
So, what can we do with structs? Well, we can print them out, though we have to do so by each individual field. We can also assign structures to each other, which might seem odd. But it’s totally doable in C. And we can have arrays of structs! And we can use initializers for our structs, like so:
Pokemon myAmpharos = {181, 100, 230, 104};We can also return structs from functions, or pass them TO functions:
Pokemon TheVeryBest(Pokemon mons[], int size)
{
int bestIndex;
for(int i = 0; i < size; ++i)
{
if(mons[i].level == 100)
{
bestIndex = i;
}
}
return mons[bestIndex];
}