Back to A Brief Guide to C


Structures (structs) are really amazingly useful constructs which package related variables. Here's the simplest way to call them:
01 struct foo {
       unsigned short int bar;
       char baz[15];
       float qux;
   };

   int main() {
08     struct foo myfoo; /* instantiate a foo struct called 'myfoo' */
    
09     myfoo.bar = 42;
       myfoo.baz = "Towel";
       myfoo.qux = (float)myfoo.bar * .3;
    
       return(0);
   }
  • line 01: At this line you can see the definition of the foo structure. This is not defining a specific piece of memory as you do when you create a variable (like int foo); instead, it is just defining a template for the later creation of a specific instance of the structure. Think of it sort of like defining your own type

    As you can see, you could put anything in the struct -- even other structs.

  • line 08: This line shows the creation of a variable of the foo structure type called myfoo. I'll show a way around this somewhat awkward syntax later.

  • line 09: Accessing the members of the foo struct is done with a dot.
Simple enough, eh? So how do you get around the awkward struct name variable_name syntax? Like this:
01 struct foo { /* first, define your struct */
       int bar;
       float baz;
   };

   /* this makes 'nodefoo' short for 'struct foo' */
07 typedef struct foo nodefoo; 

   int main() {
10     nodefoo mynode;
       /* etc... */
   }
  • line 01: Define a structure as I did in the first example.

  • line 07: The typedef can be used in this context to make nodefoo "mean" struct foo.
  • line 10: Because you used the typedef you can refer to the foo structure with nodefoo. A bit simpler and clearer.

Log in or register to write something here or to contact authors.