2

So I have a structure of unknown size as follows:

typedef struct a{
int id;
char *name;
enum job {builder=0, banker, baker};
} person;

person p;

and I want to count how many entries are in the struct through some sort of loop. I'm sure this is very simple and I'm just not thinking about it correctly but I can't seem to figure out how I would this without knowing its size.

So presumably I can't use:

for(i=0; i<x; i++) //where x is the size of the struct
{
   if(p.id!=0)
      count++;
}

what am i missing here?

Daniel Nill
  • 5,539
  • 10
  • 45
  • 63

3 Answers3

3

A struct is a template for laying out memory.

A variable is a name that has a value, sometimes that value is a bunch of memory laid out according to a struct.

Sometimes that variable is a pointer (possibly pointing to to a bunch of structs laid out in memory). Sometimes that variable is an array (possibly of structs).

Since you didn't indicate more than one "person struct" when defining the variable p, you only have one struct to count in "p"

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
1

You can't do this through a loop. You will have to do this by checking each member explicilty.

Johan Kotlinski
  • 25,185
  • 9
  • 78
  • 101
1

Assuming you actually have an array of these structs, then you can use a pointer:

person people[100];

person *p = people;
for(i=0; i<100; i++) 
{
    if (p->id != 0)
    {
      count++;
    }

    p++;
}
Peter K.
  • 8,028
  • 4
  • 48
  • 73