Hard-coded instances


#1

I’m concerned about instances of a struct being hard-coded as per the book’s examples. For example, I have defined a typedef struct called Member and two instances called a and b:

typedef struct {int strength; int gamesPlayed;} Member;

Member a;Member b;

then I have set the instance variables for these Members, eg

a.strength = 41;

and so on. But surely this is a heinous programming crime? In a real app I’d absolutely need a variable reference to specific, programmatically defined instances of Member, rather than the hard-coded a or b. I’m desparate to use arrays here, but I can’t see how an array can change these a and b instances in the code. Will my confusion be cleared up later in the book?


#2

There is no crime being committed here; they are just keeping the examples simple, for pedagogical reasons.

Here is how you could set up an array of members and iterate through them:

typedef struct {int strength; int gamesPlayed;} Member;
...
Member a;
Member b;
...
a.strength = 41;
...
Member *members [] = {&a, &b};
const long MC = sizeof (members) / sizeof (members [0]);

for (long x = 0; x < MC; ++x)
{
    Member *m = members [x];    // reference
    Member mv = *members [x];   // copy
}

Member members2 [] = {{2,3}, {5, 7}, {11, 13}};
const long MC2 = sizeof (members2) / sizeof (members2 [0]);

for (long x = 0; x < MC2; ++x)
{
    Member *m = &members2 [x];  // reference
    Member mv = members2 [x];   // copy
} 

#3

Well I don’t understand any of that, but no matter, I’ll ignore it and hope that my question about clearing up my confusion can be answered in the affirmative, and hopefully in a way that I can actually understand (by the time the clarification is made).