Main Content

Structures v Structure Pointers in C. How, which, why.

Archive - Originally posted on "The Horse's Mouth" - 2011-01-25 04:28:16 - Graham Ellis

A Structure in C is a series of sequential memory locations in which you may store and access all the various attributes of a piece of composite data; you define what each of the member elements is with a typedef and then declare variables of that new type. There's a simple example [here] which defines a data type "health" with two float members - h and w for height and weight:

  typedef struct {
    float h;
    float w;
    char name[21]; } health;


You can then declare as many variables as you like of this data type, for example:
  health primeminister;
and reference the members using a dot notation, for example:
  primeminister.w = 80;
  strncpy(primeminister.name,"David C",20)

and you can pass the data (using the single name) into functions too.

But when you pass a struct variable in to a function, you may be copying quite a bit of data and you are certainly copying the data. Which is less than efficient, and means that you're not able to return any changes within the structure - altering a copy does not mean that you alter the original, which remains unchanged in the calling code.

This issue of efficiency and flexibility is usually solved by using (and passing) pointers to structures rather than structures themselves. The variable will be declared as a pointer, and you'll need to take the additional step of ensuring that there's memory allocated for it too:
  health *primeminister;
  primeminister = (health *)calloc(1,sizeof(health));

You can then reference it through the "." notation using pointers:
  (*primeminister).h = 1.78;
But that gets a bit messy, so there's a shorthand ( ->) which you can use instead:
  primeminister->w = 85;

Full source example, using a struct pointer, is [here] to compare to the previous one that just used a straight struct.

You are strongly advised to use struct pointers most of the time; they're efficiently passed around, provide an easy route to modifying your data, and allow you far more control over the persistence of the object, as you're at liberty to allocate it on the heap and retain it until it's no longer needed, rather than using a default scoping as supplied to local variables on the stac, or global ones via extern.

Example ... from yesterday's Programming in C course.


Other examples:
basic structure setup and use - a first example
Struct and struct pointers in same program
reading a file into an array os structs