ZetCode

K&R C structures

last modified December 5, 2026 K&R C 1978

A structure groups several variables, possibly of different types, under one name. A point has two coordinates, a rectangle two points, and an entry of a table a word and a count. This article declares and initializes structures, reaches them through pointers, passes them to functions, builds arrays of structures and structures that point to each other, and then looks at what the PDP-11 compiler did with member names and how large structures are on each machine.

Declaring structures

A structure declaration starts with the keyword struct, followed by an optional name called the structure tag and a list of member declarations in braces. The declaration describes a template; no storage is set aside until variables of the type are declared.

point.c
#include <stdio.h>

struct point {
    int x;
    int y;
};

int main()
{
    struct point a, b;

    a.x = 3;
    a.y = 4;
    b.x = a.x * 2;
    b.y = a.y - 10;
    printf("a = (%d, %d)\n", a.x, a.y);
    printf("b = (%d, %d)\n", b.x, b.y);
    return 0;
}

struct point has two int members, x and y. Once the tag is declared, struct point a, b; declares two variables of that type. A member is selected with the dot operator: a.x is the x member of a, and it can be used wherever an int variable can.

$ gcc -std=c89 -pedantic -Wall -Wextra -o point point.c
$ ./point
a = (3, 4)
b = (6, -6)

Initializing structures

External and static structures can be initialized with a list of constants in braces, one for each member in order, as arrays are. A structure that is not initialized gets zeros if it is external or static. An automatic structure cannot be initialized, for the same reason an automatic array cannot.

init.c
#include <stdio.h>

struct point {
    int x;
    int y;
};

struct point origin = { 0, 0 };

struct planet {
    char *name;
    int moons;
    double radius;          /* in kilometres */
} home = { "Earth", 1, 6371.0 };

struct point last;          /* external: all members are zero */

int main()
{
    static struct point corner = { 640, 480 };
    static struct planet next = { "Mars", 2, 3389.5 };

    printf("origin (%d, %d), corner (%d, %d), last (%d, %d)\n",
        origin.x, origin.y, corner.x, corner.y, last.x, last.y);
    printf("%s: %d moon, radius %f km\n", home.name, home.moons,
        home.radius);
    printf("%s: %d moons, radius %f km\n", next.name, next.moons,
        next.radius);
    return 0;
}

origin is an external structure with an initializer. The declaration of struct planet declares the tag and the variable home at once: the variable names follow the closing brace. The local structures corner and next are static, so they may be initialized. last has no initializer; as an external variable it starts with both members zero.

$ gcc -std=c89 -pedantic -Wall -Wextra -o init init.c
$ ./init
origin (0, 0), corner (640, 480), last (0, 0)
Earth: 1 moon, radius 6371.000000 km
Mars: 2 moons, radius 3389.500000 km

Nested structures

A member can itself be a structure. A rectangle can be described by two points at opposite corners, and a structure for it then contains two struct point members.

nested.c
#include <stdio.h>

struct point {
    int x;
    int y;
};

/* a rectangle given by two opposite corners */
struct rect {
    struct point pt1;
    struct point pt2;
};

struct rect screen = { { 0, 0 }, { 640, 480 } };
struct rect window = { { 100, 50 }, { 420, 290 } };

int main()
{
    int width, height;

    width = window.pt2.x - window.pt1.x;
    height = window.pt2.y - window.pt1.y;
    printf("window: %d x %d at (%d, %d)\n", width, height,
        window.pt1.x, window.pt1.y);

    if (window.pt1.x >= screen.pt1.x && window.pt2.x <= screen.pt2.x
        && window.pt1.y >= screen.pt1.y && window.pt2.y <= screen.pt2.y)
        printf("the window fits on the screen\n");

    window.pt2.x += 300;
    if (window.pt2.x > screen.pt2.x)
        printf("now it does not: pt2.x = %d\n", window.pt2.x);
    return 0;
}

The initializer of a nested structure has inner braces for each inner structure. window.pt2.x selects the member pt2 of window and then its member x; the dot operator groups from left to right. The program computes the size of the window, tests whether it lies inside the screen, and then moves its right edge out of the screen.

$ gcc -std=c89 -pedantic -Wall -Wextra -o nested nested.c
$ ./nested
window: 320 x 240 at (100, 50)
the window fits on the screen
now it does not: pt2.x = 720

Pointers to structures

The address of a structure is taken with &, and a pointer to a structure is declared like any other pointer. Members are reached through the pointer often enough that the language has a separate operator for it.

pstruct.c
#include <stdio.h>

struct point {
    int x;
    int y;
};

struct rect {
    struct point pt1;
    struct point pt2;
};

int main()
{
    struct point a;
    struct point *pp;
    struct rect r;
    struct rect *rp;

    pp = &a;
    (*pp).x = 3;
    pp->y = 4;
    printf("a = (%d, %d)\n", a.x, pp->y);

    rp = &r;
    rp->pt1.x = rp->pt1.y = 1;
    rp->pt2.x = a.x;
    rp->pt2.y = a.y;
    printf("r = (%d, %d) - (%d, %d)\n", r.pt1.x, r.pt1.y,
        (rp->pt2).x, rp->pt2.y);
    return 0;
}

(*pp).x is the x member of the structure pp points to. The parentheses are necessary, because the dot binds more tightly than *: *pp.x would mean *(pp.x). pp->y is a shorthand for (*pp).y. The operators . and -> both group from left to right, so rp->pt1.x is the x member of the pt1 member of the rectangle that rp points to. Copying the point a into the rectangle is done one member at a time.

$ gcc -std=c89 -pedantic -Wall -Wextra -o pstruct pstruct.c
$ ./pstruct
a = (3, 4)
r = (1, 1) - (3, 4)

Structures and functions

In the language of the book, the only operations on a structure are taking its address and selecting its members. A structure cannot be assigned as a whole, passed to a function, or returned from one. Functions therefore work with pointers to structures, which is also cheaper than copying the members.

funcs.c
#include <stdio.h>

struct point {
    int x;
    int y;
};

struct rect {
    struct point pt1;
    struct point pt2;
};

/* fill in the point p points to */
int makepoint(p, x, y)
struct point *p;
int x, y;
{
    p->x = x;
    p->y = y;
    return 0;
}

/* copy a point member by member */
int copypoint(to, from)
struct point *to, *from;
{
    to->x = from->x;
    to->y = from->y;
    return 0;
}

int area(r)
struct rect *r;
{
    return (r->pt2.x - r->pt1.x) * (r->pt2.y - r->pt1.y);
}

int main()
{
    struct point a, b;
    struct rect r;

    makepoint(&a, 2, 3);
    makepoint(&b, 12, 8);
    copypoint(&r.pt1, &a);
    copypoint(&r.pt2, &b);
    printf("(%d, %d) - (%d, %d)\n", r.pt1.x, r.pt1.y, r.pt2.x, r.pt2.y);
    printf("area: %d\n", area(&r));
    return 0;
}

makepoint fills in the structure its first argument points to, and copypoint copies a point member by member. In an old-style definition, a pointer parameter is declared as struct point *p;. area only reads the rectangle, but it still receives a pointer. &r.pt1 is the address of the member pt1, since . binds more tightly than &. The book says that the restrictions on structures would be lifted in later versions of the language. The V7 compiler already accepts structure assignment, and the porting article shows the later forms.

$ gcc -std=c89 -pedantic -Wall -Wextra -o funcs funcs.c
$ ./funcs
(2, 3) - (12, 8)
area: 50

Arrays of structures

A table of related values is an array of structures. The next program counts the occurrences of some C keywords in its input. Each entry of the table holds a keyword and its count, so the two values stay together.

kwcount.c
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAXWORD 20

struct key {
    char *word;
    int count;
} keytab[] = {
    { "char", 0 },
    { "else", 0 },
    { "for", 0 },
    { "if", 0 },
    { "int", 0 },
    { "return", 0 },
    { "while", 0 }
};

#define NKEYS (sizeof keytab / sizeof keytab[0])

/* read the next word of letters and digits into w */
int getword(w, lim)
char *w;
int lim;
{
    int c;

    while ((c = getchar()) != EOF && !isalpha(c))
        ;
    if (c == EOF)
        return EOF;
    *w++ = c;
    while (--lim > 1 && (c = getchar()) != EOF && isalnum(c))
        *w++ = c;
    *w = '\0';
    return 1;
}

int main()
{
    char word[MAXWORD];
    struct key *p;

    while (getword(word, MAXWORD) != EOF)
        for (p = keytab; p < keytab + NKEYS; p++)
            if (strcmp(word, p->word) == 0)
                p->count++;

    for (p = keytab; p < keytab + NKEYS; p++)
        if (p->count > 0)
            printf("%s %d\n", p->word, p->count);
    return 0;
}

The declaration of struct key also defines the array keytab and initializes it; the inner braces group the members of each element. NKEYS computes the number of entries from the size of the array, so the table can grow without changing the code. getword skips everything up to the next letter and then collects letters and digits. The loops walk the table with a pointer: keytab + NKEYS is the address just past the last element, and p++ advances by the size of a whole structure.

lines.txt
int lower(c)
int c;
{
    if (c >= 'A' && c <= 'Z')
        return c + 'a' - 'A';
    else
        return c;
}

int length(s)
char s[];
{
    int i;

    for (i = 0; s[i] != '\0'; i++)
        ;
    return i;
}

The input is a piece of K&R C code: two small functions.

$ gcc -std=c89 -pedantic -Wall -Wextra -o kwcount kwcount.c
$ ./kwcount < lines.txt
char 1
else 1
for 1
if 1
int 4
return 3

Self-referential structures

A structure cannot contain a member of its own type, but it can contain a pointer to its own type. Such structures link to one another and form lists and trees.

list.c
#include <stdio.h>

struct node {
    int value;
    struct node *next;
};

struct node n3 = { 30, 0 };
struct node n2 = { 20, &n3 };
struct node n1 = { 10, &n2 };
struct node extra = { 15, 0 };

int printlist(p)
struct node *p;
{
    for (; p != 0; p = p->next)
        printf("%d ", p->value);
    printf("\n");
    return 0;
}

int main()
{
    struct node *head;

    head = &n1;
    printlist(head);

    extra.next = n1.next;       /* insert extra after n1 */
    n1.next = &extra;
    printlist(head);

    head = head->next;          /* drop the first node */
    printlist(head);
    return 0;
}

Each struct node holds a value and a pointer to the next node; the last node has the null pointer 0. The external nodes are linked by their initializers, which may contain the addresses of external variables. printlist follows the next pointers until it reaches 0. A node is inserted by changing two pointers, and the list loses its first node when head moves on. The linked lists and binary trees articles allocate the nodes at run time.

$ gcc -std=c89 -pedantic -Wall -Wextra -o list list.c
$ ./list
10 20 30 
10 15 20 30 
15 20 30 

Type names with typedef

The typedef declaration creates a new name for a type. It is written like a variable declaration with typedef in front, and the name in the place of the variable becomes the name of the type. It does not create a new type; it only gives an existing one a shorter or clearer name.

typedf.c
#include <stdio.h>

typedef int LENGTH;
typedef char *STRING;

typedef struct point {
    int x;
    int y;
} POINT;

typedef struct node *LINK;

struct node {
    STRING name;
    LINK next;
};

LENGTH length(s)
STRING s;
{
    LENGTH n;

    for (n = 0; *s != '\0'; s++)
        n++;
    return n;
}

int main()
{
    static struct node b = { "beta", 0 };
    static struct node a = { "alpha", &b };
    POINT p;
    LINK q;

    p.x = 5;
    p.y = 7;
    printf("p = (%d, %d)\n", p.x, p.y);
    for (q = &a; q != 0; q = q->next)
        printf("%s has %d characters\n", q->name, length(q->name));
    return 0;
}

LENGTH is a synonym for int, and STRING for char *. POINT names the structure type declared in the same statement, and LINK is a pointer to struct node, declared before the structure itself. Writing type names in capitals sets them apart from variables. A typedef can make a program clearer, and it collects the machine-dependent types of a program in one place.

$ gcc -std=c89 -pedantic -Wall -Wextra -o typedf typedf.c
$ ./typedf
p = (5, 7)
alpha has 5 characters
beta has 4 characters

Member names

In the language of the book, the members and tags of all structures share one name space. A member name stands for an offset from the start of a structure, and the same name may appear in two structures only if it has the same type and offset in both.

members.c
#include <stdio.h>

struct point {
    int x;
    int y;
};

struct box {
    int width;
    int x;          /* at a different offset than point.x */
};

int main()
{
    struct box b;

    b.width = 10;
    b.x = 2;
    printf("width %d at x = %d\n", b.width, b.x);
    return 0;
}

x is the first member of struct point but the second member of struct box. GCC keeps a separate set of member names for each structure and compiles the program.

$ gcc -std=c89 -pedantic -Wall -Wextra -o members members.c
$ ./members
width 10 at x = 2

The PDP-11 compiler rejects the second x. This is why the structures of UNIX give their members a prefix, as in st_size and st_mode in the stat structure or tm_year in tm.

$ cc members.c
members.c:10: x redeclared

Members as offsets

Because a member name is just an offset, the PDP-11 compiler does not check that the pointer on the left of -> points to the right structure, or to a structure at all.

arrow.c
#include <stdio.h>

struct point {
    int x;
    int y;
};

int main()
{
    static int v[] = { 10, 20, 30 };
    int *ip;

    ip = v;
    printf("%d\n", ip->y);
    return 0;
}

ip is a pointer to int, and ip->y asks for the member y of struct point through it. GCC refuses: -> needs a pointer to a structure that has the member.

$ gcc -std=c89 -pedantic -Wall -Wextra -o arrow arrow.c
arrow.c: In function ‘main’:
arrow.c:14:22: error: request for member ‘y’ in something not a structure or union
   14 |     printf("%d\n", ip->y);
      |                      ^~

On the PDP-11, ip->y adds the offset of y, two bytes, to the address in ip and reads the int found there: the second element of the array. Early UNIX code used this to reach machine registers and fields of words at fixed addresses.

$ cc arrow.c
$ a.out
20

Structure sizes

The size of a structure is at least the sum of the sizes of its members. It can be larger, because the machine may require some types to start at an even address or at a multiple of their size, and the compiler then leaves unused bytes, called padding, between the members.

ssizes.c
#include <stdio.h>

struct chars {
    char c_first, c_second, c_third;
};

struct withint {
    char i_tag;
    int i_val;
};

struct withlong {
    char l_tag;
    long l_val;
};

struct withdouble {
    char d_tag;
    double d_val;
};

int main()
{
    printf("chars:      %d\n", (int) sizeof(struct chars));
    printf("withint:    %d\n", (int) sizeof(struct withint));
    printf("withlong:   %d\n", (int) sizeof(struct withlong));
    printf("withdouble: %d\n", (int) sizeof(struct withdouble));
    return 0;
}

The structures have a char followed by a larger member. The members have prefixes, so the program also compiles on the PDP-11. On x86-64, an int starts at a multiple of 4 and a long or double at a multiple of 8, so a single char in front costs 3 or 7 bytes of padding.

$ gcc -std=c89 -pedantic -Wall -Wextra -o ssizes ssizes.c
$ ./ssizes
chars:      3
withint:    8
withlong:   16
withdouble: 16

The PDP-11 aligns every type larger than a char on an even address, so one byte of padding follows the char. A long takes 4 bytes and a double 8. The compiler also rounds every structure up to an even size, so the three characters take 4 bytes. A program that writes structures to a file and reads them back on another machine, or computes offsets by hand, must take these differences into account; sizeof always gives the right size for the machine at hand.

$ cc ssizes.c
$ a.out
chars:      4
withint:    4
withlong:   6
withdouble: 10

Source

Dennis Ritchie: C Reference Manual (1975)

GCC: Structures, Unions, Enumerations, and Bit-Fields

In this article we have worked with structures in K&R C: declarations and initialization, nested structures, pointers to structures and the -> operator, functions that receive structures by pointer, arrays of structures, self-referential structures, typedef, the shared member names of the PDP-11 compiler, and structure sizes. The next article covers unions and bit-fields.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.