Understanding structs and typedef


It took me a while to get through my thick head just exactly what struct does and how much neater typedef makes them. Every book I’ve seen defines a struct using words too close to the struck name, like:

struck person { *bunch of members* }; typedef struct person person;


typedef struct { *bunch of members* } person;

Then they go on to use:

person person;

It wasn’t until I started using it like:

person daniel;  or:
person courtney

…that I finally disassociated the type from the instance and started having some fun with it. Imagine, I’m creating my own type and am able to access the instance data like:


If the books would do the same, perhaps it would be easier to understand from the beginning. Any comments?


Good discovery; you are becoming a real programmer now :slight_smile:

To confuse you a bit, you can also put the typedef before the struct declaration:

typedef struct Foo Foo;
struct Foo
   char buffer [512];
   Foo *next;

Which is equivalent to:

struct Foo
   char buffer [512];
   struct Foo *next;

See Also: viewtopic.php?f=162&t=4311&p=10393#p10350

As for whether the book should have taken a different approach, it is hard to say. The author has done an excellent job considering the physical size of the book.

If you would like to deepen your understanding of the C language (in order to appreciate the Objective-C language):
Here is a book worth reading: “The C Programming Language, Brian W. Kernighan and Dennis M. Ritchie.” by the people who created the C language.


Ha, ha. Had to study that for a while. But I think I’ll stick with a syntax I’m most comfortable with. Thanks, if I ever run across that construct at least I’ll understand what that evil programmer was trying to do :slight_smile:

Your K&R recommendation is not the first time I’ve heard this. I think I’ll give Amazon a shout.


This was a helpful discussion. After reading the other posts, I modified the example in the book to make it a bit clearer for me;

[code]#include <stdio.h>

//Here is a declaration of the struct Person
typedef struct Human {
float heightInMeters;
int weightInKilos;
} Person;

int main(int argc, const char * argv[])
Person Bob; //You could replace this line with 'struct Human Bob;'
printf(“Bob weighs %i kilograms\n”,Bob.weightInKilos);
printf(“Bob is %.2f meters tall\n”,Bob.heightInMeters);
return 0;