Main Content

C Structs - what, how and why

Archive - Originally posted on "The Horse's Mouth" - 2010-01-13 08:20:08 - Graham Ellis

If you want to hold a whole series of different values about something in a C program, you'll define yourself a structure (or struct.). You give a type and name to each of the elements in the structure, and then you give an overall variable name to each instance of the struct that you create.

Here, for example, I am defining a type called "result" - to hold everything about the results of a test, for example:

typedef struct {
     int lowlim;
     int highlim;
     int pass;
     int range;
     float dut_out;
     } result;


So far, I have only defined a type .. not any actual variables that contain results; I can declare those in the way I normally declare variables, including defining pointers to them if I wish:

  result *current
  result first;
  result second;


Elements within a structure variable can be referenced (set or read) using a "." notation - for example:

  second.dut_out = 50.0;
  printf("The range was %d\n",second.range);


If you want to reference elements within a referenced struct (such as current in our example) you COULD write:
(*current).range
but that gets messy and an alternative, bracket-free notation is available:
current->range

You'll use pointers to structs very commonly indeed - to pass them around between function, to define them dynamically with calloc and realloc, etc.

Full source code example, showing all the things I have mentioned above, [HERE].