Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 135 ยท Structures and Unions

Structures

Learn C structures - define a struct, initialize it with designated initializers, access members, copy and compare structs, return them from functions and use compound literals.

So far your data has come in two shapes: single values like an int, and arrays of many values that all share one type. Real-world things rarely fit either shape. A book has a title, an author, a year and a price; a point on screen has an x and a y; a bank transaction has an amount, a date and a description. You could keep each piece in its own variable, but nothing would tie them together, and every function would need half a dozen parameters.

A structure (struct) groups related values of different types into one new type. Each value inside is a member (or field) with its own name and type. Structures are the main tool C has for modeling data, and nearly every real C program, from the Linux kernel to SQLite, is built around them. This lesson covers defining, initializing, using, copying and comparing structs; the next lessons add pointers to structs and arrays of structs.

Defining a structure

A struct definition describes the layout of a new type. It doesn't create any variable by itself:

C
struct book {
    char title[64];
    char author[48];
    int year;
    double price;
};

The name after struct is the tag. Together, struct book is the full type name, and you declare variables with it just like with int:

C
struct book favorite;              /* one book */
struct book shelf[10];             /* an array of ten books */

Notice the semicolon after the closing brace. Forgetting it is a classic mistake, and the compiler's error usually points at the next line, which makes it confusing the first time.

Members can be of any complete type: numbers, characters, arrays, pointers, other structs, enums. A struct can't contain itself (it would be infinitely large), but it can contain a pointer to its own type, which is how linked lists are built (Structures and Pointers).

Accessing members with the dot operator

You reach a member with a dot: favorite.year is an ordinary int variable that happens to live inside favorite. You can read it, assign it, take its address and pass it to functions like any other variable.

C Your first struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Array members like title behave like any array: you can't assign a string to them with =, so the example copies text in with snprintf, which never writes more than sizeof favorite.title bytes (see Safe String Handling).

Initializing a struct

Writing members one by one is tedious and easy to get wrong. Like arrays, structs can be initialized with a braced list when they are declared.

Positional initializers list values in member order:

C
struct book b1 = {"Notes on Tides", "M. Laurent", 2021, 18.50};

That's compact, but it silently breaks if someone reorders or inserts members later. Designated initializers (C99) name each member, so order doesn't matter and the code documents itself:

C
struct book b2 = {
    .title = "Notes on Tides",
    .author = "M. Laurent",
    .year = 2021,
    .price = 18.50,
};

Two rules make initializers very convenient:

  • Members you leave out are zero-initialized. Numbers become 0, pointers become null and character arrays become empty strings. This applies whenever any initializer is present.
  • = {0} zeroes a whole struct, and C23 also accepts the empty initializer = {} for the same purpose.
C Designated initializers and default zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

custom names only two members, so its width, height and gamma are all zero. That makes designated initializers a natural way to express "everything off except these options". Without any initializer at all, a local struct is uninitialized like any local variable, and reading its members is undefined behavior.

Tip: prefer designated initializers for any struct with more than two or three members. A trailing comma after the last member is allowed, which keeps diffs clean when you add fields.

Copying structs

Unlike arrays, structs can be assigned, passed to functions and returned from functions as whole values. Assignment copies every member, byte for byte, including arrays inside the struct:

C Assignment copies the whole struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Changing copy leaves original alone: the names are Mina and Tina, and the first scores are 10 and 99. The array members were copied element by element. The team member, however, is a pointer, and copying a pointer copies only the address. Both structs now point at the same string, and the program confirms it with same team string? yes.

This is called a shallow copy. It's exactly right for numbers and embedded arrays, and dangerous for pointers that own heap memory: if both copies later call free on the same pointer, you have a double free. A struct that owns memory usually needs its own copy function that allocates fresh memory for the pointed-to data (a deep copy).

Comparing structs

C has no == for structs. if (a == b) doesn't compile. You compare member by member, usually in a small function:

C
bool point_equal(struct point a, struct point b)
{
    return a.x == b.x && a.y == b.y;
}

You may be tempted to use memcmp(&a, &b, sizeof a). Don't, as a rule. Structs can contain padding bytes between members (the compiler inserts them for alignment; see Padding and Alignment), and their values are unspecified, so two structs with equal members can still differ byte-wise. memcmp also compares pointers by address rather than the strings they point to, and treats 0.0 and -0.0 as different.

Structs and functions

Passing a struct to a function copies it, just like passing an int. The function works on its own copy, so changes don't affect the caller. Returning a struct is equally natural, and it's a clean way for a function to return several values at once:

C Returning a struct from a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Inside try_to_reset the minimum is 0, but back in main the output is still min 9, max 23, mean 16.14: the function changed only its copy. Copying is cheap for small structs like this one (16 bytes). For large structs, say one holding a 4 KB buffer, passing by value copies all of it on every call. Then you pass a pointer instead, preferably a const pointer when the function only reads: void print_book(const struct book *b). That's the main topic of Structures and Pointers.

Compound literals

A compound literal (C99) creates an unnamed struct value on the spot. You write the type in parentheses followed by an initializer list: (struct point){.x = 3, .y = 4}. It's handy for passing a struct to a function without declaring a variable, or for resetting a struct in a single assignment:

C Compound literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The distances are 5.0 and 10.0. Assigning a compound literal replaces every member, so cursor becomes (1, 0), not (1, 10). A compound literal is an actual object (an lvalue), so you can even take its address. Inside a function it lives until the end of the enclosing block, like a local variable, so don't return its address.

typedef and anonymous members

Writing struct before every use is the C tradition, and many style guides (the Linux kernel's, for example) prefer it because it makes clear that a type is a struct. Others create an alias with typedef:

C
typedef struct {
    double x;
    double y;
} Point;

Point p = {1.5, 2.5};       /* no "struct" keyword needed */

Both styles are fine; pick one per project and stay consistent.

C11 added anonymous structs and unions as members: a nested struct without a name whose members you access as if they belonged to the outer struct. They're mostly used together with unions:

C
struct vector3 {
    union {
        struct { float x, y, z; };   /* anonymous struct */
        float components[3];
    };
};

struct vector3 v = {.x = 1.0f};      /* v.x, v.components[0]: same memory */

Self-referential structures

A structure cannot contain a member of its own type, because it would have to be infinitely large. It can contain a pointer to its own type, because every pointer has a fixed size. A struct with such a member is called self-referential, and it is the building block of linked lists, trees and graphs:

C
struct node {
    int value;
    struct node *next;      /* a pointer to another node: fine */
};

Trying the by-value version fails to compile:

C
struct bad {
    int value;
    struct bad inner;       /* error: field 'inner' has incomplete type */
};

Inside its own definition struct bad is still incomplete: the compiler does not yet know its size, so it cannot reserve space for a member of that type. A pointer to an incomplete type is allowed, because the compiler only needs the size of the pointer.

The tag is required. With typedef, the alias does not exist yet inside the braces, so the member must use the struct tag:

C
typedef struct node {
    int value;
    struct node *next;      /* "Node" is not declared yet here */
} Node;

Node *head = NULL;          /* outside, the short name works */

A tree node is the same idea with two pointers, left and right. Declaring a pointer member does not allocate anything; the pointer starts out pointing nowhere, so give it NULL for "no neighbor" and check before following it. Linked Lists builds a full list on this pattern.

Two structs that refer to each other

Sometimes two different structs need pointers to each other: a department has employees, and every employee knows their department. Neither definition can come first with a complete type, so use a forward declaration, which announces that a struct tag exists without defining it:

C
struct department;                     /* forward declaration: incomplete for now */

struct employee {
    const char *name;
    struct department *home;           /* pointer to an incomplete type: fine */
    struct employee *manager;          /* and a self-reference too */
};

struct department {
    const char *title;
    struct employee *staff[4];
    int staff_count;
};
C Employees, managers and departments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The chain for Lena walks up through manager until the pointer is NULL, which is exactly how a linked list is traversed. The home pointers lead the other way, back to the department. Because both structs live in main, everything is valid until main ends; with heap-allocated nodes, you must also decide who calls free (Dynamic Memory).

Mutually referencing types can also be forward-declared with typedef, so the short names work inside both definitions:

C
typedef struct employee Employee;      /* both names exist, type incomplete */
typedef struct department Department;

struct employee   { const char *name; Department *home; Employee *manager; };
struct department { const char *title; Employee *staff[4]; int staff_count; };

This is the style many large C projects use: declare all the type aliases in one header, define the structs where they belong. See also Structs and Pointers.

How big is a struct?

sizeof works on structs and gives the total size in bytes. It's often more than the sum of the members' sizes, because the compiler adds padding to keep each member aligned. On our 64-bit system, struct { char tag; double value; } is 16 bytes, not 9. You'll explore why, and how to use offsetof to see the layout, in Padding and Alignment. For now, the rule is simple: always use sizeof, never add up member sizes by hand.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. struct item { int id; double weight; int count; }; What does struct item a = {.count = 5}; set id and weight to?

    When any initializer is present, every member you don't mention is zero-initialized.
  2. 2. struct tag { char label[8]; int *ptr; }; After struct tag b = a;, which statement is true?

    Assignment copies all members by value. The array is copied element by element, but a pointer copy duplicates only the address (a shallow copy).
  3. 3. How do you correctly check whether two struct point values are equal?

    C has no == for structs, and memcmp can be fooled by padding bytes, pointer members and special float values like -0.0.
  4. 4. What does this print? struct p { int x, y; }; struct p a = {.x = 3, .y = 4}; a = (struct p){.y = 9}; printf("%d %d", a.x, a.y);

    The compound literal is a complete struct value with x zero-initialized, and assignment replaces every member.
  5. 5. A function takes a 4 KB struct by value but only reads it. What is the usual improvement?

    Passing by value copies all 4 KB on every call. A const pointer passes only an address and still guarantees the function won't modify it.

Summary

  • A struct groups members of different types into one new type. struct tag { ... }; defines it; don't forget the final semicolon.
  • Access members with the dot operator: book.year.
  • Initialize with braces; designated initializers (.year = 2021) are clearer and robust to reordering. Members you omit become zero, and = {0} (or C23 = {}) zeroes everything.
  • Structs can be assigned, passed and returned by value. The copy is shallow: arrays inside are copied, but pointers still share what they point to.
  • There's no == for structs; compare members in a function, and avoid memcmp because of padding.
  • Compound literals like (struct point){.x = 3} create unnamed struct values on the spot.
  • sizeof a struct may include padding, so always use sizeof rather than adding member sizes.

Next: Structures and Pointers, where you'll use the arrow operator, pass structs efficiently and build structs on the heap.