TOC | Prev | Next

Pointers to structs

Dereferencing struct pointers can be done in one of two ways:

(*p).member = x;
p->member   = x;
*p.member   = x; /* WRONG */
*(p.member) = x; /* WRONG, same as above */

Here's the right way, with an example of typedefs, too.

struct-pointers.c

#include <stdio.h>
#include <string.h>

typedef struct employee_t {
    char name[40];
    int onsite;
    struct {
        int floor;
        char quadrant;
        int cube;
    } location;
} employee;

void assign_location( employee *who );

int main( void ) {
    employee me;
    strcpy( me.name, "Andy Lester" );

    assign_location( &me );

    if ( me.onsite ) {
        printf( "%s is at location %d%c-%d\n", me.name,
                me.location.floor, me.location.quadrant, me.location.cube );
    }

    return 0;
}

void assign_location( employee *who ) {
    who->location.floor    = 4;
    who->location.quadrant = 'B';
    who->location.cube     = 14;
    who->onsite            = 1;
}

$ struct-pointers

Andy Lester is at location 4B-14
TOC | Prev | Next