Thuta Learning
C
AdvancedProgrammingBeginner

Structures

CLesson 2830 min

What you'll walk away with

  • Define a struct type and initialize it both positionally and with designated initializers
  • Reach members with . on a struct and with -> on a pointer to a struct
  • Predict what struct assignment copies and decide when to pass a struct by pointer
  • Explain why the sizeof a struct can exceed the sum of its members

Explain it simply

Explain it simply

A struct is a custom type that bundles several related values under one name. A student is not just a name, or just an age, or just a score: it is all three together, and struct Student lets you treat them as a single thing that you can store, copy, pass to a function and keep in an array.

Each value inside is called a member (or field), and every member can have its own type: a char array for the name, an int for the age, a float for the score. You reach a member with a dot, as in s1.age, much like asking for one box on a form.

Problem → Why → Solution

The problem: parallel arrays drift apart

Without structs, a class list is usually kept in parallel arrays: names in one array, ages in a second, scores in a third, linked only by sharing an index. That works until someone sorts the scores and forgets to move the matching names and ages. In the program below the highest score ends up attached to the wrong student, and the compiler has no way to notice.

class_list.c
#include <stdio.h>

int main(void) {
    char names[3][30] = {"Sai", "Mya", "Ko Ko"};
    int ages[3] = {20, 19, 21};
    float scores[3] = {86.5f, 91.0f, 78.0f};

    /* "sort" by score: swap entries 0 and 1 ... but only in scores[] */
    float tmp = scores[0];
    scores[0] = scores[1];
    scores[1] = tmp;

    /* prints "Top student: Sai (20) with 91.0" - Mya scored 91.0 */
    printf("Top student: %s (%d) with %.1f\n", names[0], ages[0], scores[0]);
    return 0;
}

Why does the data stop matching?

Parallel arrays keep the pieces of one record in three unrelated places, so every operation, whether sorting, inserting, deleting or passing data to a function, must remember to touch all of them in the same way. A struct stores the pieces of one record side by side in a single object. Swapping two struct Student values moves the name, age and score together, and a function takes one parameter instead of three.

Core concept: a struct is a value

A struct declaration creates a new type: struct Student { char name[30]; int age; float score; }; describes a layout but reserves no memory. Memory is reserved when you declare a variable of that type, struct Student s1;. You can initialize it positionally, {"Sai", 20, 86.5f}, where the values match the members in order, or with designated initializers, {.name = "Mya", .age = 19}, which name each member. Members you leave out of an initializer are set to zero.

The dot operator selects a member of a struct object: s1.age. When all you have is a pointer, use the arrow: p->age means exactly (*p).age, that is, follow the pointer and then select the member. The parentheses in (*p).age matter because . binds more tightly than *, which is why -> exists. Functions usually take const struct Student * for reading and struct Student * for changing, because passing the address copies 8 bytes instead of the whole struct.

Structs behave like values. struct Student copy = s1; copies every member, including a char array member, so the copy has its own name buffer. Passing a struct to a function by value gives the function its own copy as well, so changes made inside never reach the caller. Assignment works, but == does not: GCC rejects a == b on two structs with invalid operands to binary ==. Compare the members you care about yourself, typically in a helper function.

Inside a struct the compiler may insert padding so that each member sits at an address suited to its type: on x86-64 an int usually starts at a multiple of 4 and a double at a multiple of 8. That is why sizeof(struct Student) is 40 with GCC on 64-bit Windows and Linux (30 + 2 padding + 4 + 4), not 38. Members are always stored in the order you declare them, so putting the largest first can shrink a struct, and padding is one reason a struct's raw bytes are not a portable file format.

Mental model: a form with labelled boxes
  1. Define the form: struct T { ... };
  2. Fill one in: struct T x = {...};
  3. Read a box: x.member or p->member
  4. Copying copies every box

A struct is a value: assignment copies it, == cannot compare it, and padding may make it larger than its parts.

General pattern

c
struct Name {
    type1 member1;
    type2 member2;
};

struct Name a = {value1, value2};      /* positional */
struct Name b = {.member2 = value2};   /* designated; member1 becomes 0 */

a.member1 = value;                     /* dot on a struct object */
struct Name *p = &a;
p->member1 = value;                    /* arrow on a pointer: (*p).member1 */

Do not forget the semicolon after the struct definition. A positional initializer follows the member order, a designated one picks members by name. Use . on an object and -> on a pointer.

Example: student records

The program builds two students with the two kinds of initializer, then uses one function that reads a struct through a pointer and one that modifies it. The last line proves that a struct copy has its own data: s1 changes, but copy stays at 86.5.

students.c
#include <stdio.h>

struct Student {
    char name[30];
    int age;
    float score;
};

void print_student(const struct Student *s) {
    printf("%s (age %d) scored %.1f\n", s->name, s->age, s->score);
}

void add_bonus(struct Student *s, float bonus) {
    s->score += bonus;
}

int main(void) {
    struct Student s1 = {"Sai", 20, 86.5f};
    struct Student s2 = {.name = "Mya", .age = 19, .score = 91.0f};

    printf("First student: %s\n", s1.name);
    print_student(&s1);
    print_student(&s2);

    struct Student copy = s1;   /* copies every member, name included */
    add_bonus(&s1, 5.0f);
    printf("s1.score = %.1f, copy.score = %.1f\n", s1.score, copy.score);
    return 0;
}

Code breakdown

  1. Lines 3-7struct Student {

    This defines the new type struct Student. No memory is reserved yet; that happens for the variables in main.

  2. Line 18{"Sai", 20, 86.5f}

    A positional initializer fills name, age and score in order. The f suffix makes 86.5 a float constant rather than a double.

  3. Line 19.name = "Mya"

    A designated initializer picks the member by name, so it stays correct even if the member order in the struct changes.

  4. Line 10s->name, s->age, s->score

    s is a pointer, so the members are reached with ->. The const struct Student * parameter promises that print_student never modifies the record.

  5. Line 14s->score += bonus;

    add_bonus takes a pointer, so it changes the caller's s1 itself; taking struct Student s by value would only change a copy.

  6. Line 25struct Student copy = s1;

    Every member, the name array included, is copied. That is why line 27 shows s1.score as 91.5 while copy.score is still 86.5.

You should see
First student: Sai
Sai (age 20) scored 86.5
Mya (age 19) scored 91.0
s1.score = 91.5, copy.score = 86.5

Padding and sizeof

The program below declares the same three members in two different orders. With GCC on 64-bit Windows and Linux it prints 24 for struct Loose, 16 for struct Tight and 8 for struct Small, even though the members of Loose and Tight add up to only 10 bytes and those of Small to 5.

padding.c
#include <stdio.h>

struct Loose {
    char a;
    double d;
    char b;
};

struct Tight {
    double d;
    char a;
    char b;
};

struct Small {
    char c;
    int i;
};

int main(void) {
    printf("sizeof(struct Loose) = %zu\n", sizeof(struct Loose));
    printf("sizeof(struct Tight) = %zu\n", sizeof(struct Tight));
    printf("sizeof(struct Small) = %zu\n", sizeof(struct Small));
    return 0;
}
text
Byte layout with GCC on x86-64 (each cell = 1 byte)
---------------------------------------------------
struct Loose { char a; double d; char b; };            sizeof = 24
 0  1              8                16 17             24
 +--+--------------+----------------+--+--------------+
 |a | 7 x padding  |    d (8)       |b | 7 x padding  |
 +--+--------------+----------------+--+--------------+

struct Tight { double d; char a; char b; };            sizeof = 16
 0                8  9  10            16
 +----------------+--+--+-------------+
 |    d (8)       |a |b | 6 x padding |
 +----------------+--+--+-------------+

Padding bytes have no meaningful value, and how many there are depends on the platform's alignment rules. Add byte order (endianness) and future changes to the struct, and writing a struct to a file or socket with a single fwrite() call creates a format other programs cannot reliably read. Real file formats write each member explicitly, with a documented size and byte order.

typedef and arrays of structs

typedef gives a type a second name, so after typedef struct { int x; int y; } Point; you can write Point everywhere instead of a struct keyword and tag. An array of structs keeps one record per element: path[i].x reads a member of the i-th point, and a pointer to one element uses -> like any other struct pointer.

points.c
#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

int main(void) {
    Point path[3] = {{0, 0}, {3, 4}, {6, 8}};
    Point *last = &path[2];

    for (int i = 0; i < 3; i++) {
        printf("(%d, %d)\n", path[i].x, path[i].y);
    }
    last->x = 7;
    printf("last point is now (%d, %d)\n", path[2].x, path[2].y);
    return 0;
}

In real projects

Where this shows up in real projects

Almost every C program of real size is organized around structs. The standard library uses them too: struct tm from time.h holds the parts of a calendar date, and FILE, which you used in the File I/O lesson, is in practice a struct whose members you never touch: you only ever handle it through a FILE * pointer. Operating system interfaces such as POSIX's struct stat (file information) and the address structures of network code are structs as well.

In application code, structs model the nouns of your problem: a Product with a name, price and stock, an Order holding a customer id and an array of lines, a Config filled in from a settings file. A common style pairs each struct with small functions that create, validate, print and compare it, always taking a pointer, so the rest of the program never builds a half-valid record by hand. When the data must leave the program, those same functions write it out member by member instead of dumping raw bytes.

Common mistakes

Common mistakes

1. Assigning a string to a char array member

s.name = "Mya"; fails with assignment to expression with array type, because arrays cannot be assigned in C. Copy into the array instead, for example with snprintf(s.name, sizeof s.name, "%s", "Mya");, which also stops at the buffer's size.

2. Using . on a pointer

With struct Student *p, p.age does not compile, and GCC even suggests the fix: 'p' is a pointer; did you mean to use '->'? Use p->age or the equivalent (*p).age. Writing *p.age is wrong as well, because . binds more tightly than *.

3. Comparing structs with ==

if (a == b) is rejected with invalid operands to binary ==. The usual answer is a helper such as same_student(const struct Student *a, const struct Student *b) that compares the members you care about. Avoid memcmp() on whole structs, because padding bytes may differ even when every member is equal.

4. Expecting a by-value parameter to change the caller's struct

void add_bonus(struct Student s) works on a copy, so the caller's score never changes. Pass a struct Student * when the function must modify the record.

Best practices

Best practices

  • Prefer designated initializers for structs with more than two or three members; they survive reordering and document each value.
  • Pass structs to functions as const T * for reading and T * for modifying.
  • Never write a struct's raw bytes as a file or network format; write each member explicitly.

Mini challenge

Mini challenge: a small inventory

Model the products on a shop shelf with a struct and write functions that compute and update their stock.

  • Define a Product type with typedef struct holding a name (char[20]), a quantity (int) and a price (double)
  • double stock_value(const Product *p) returns quantity times price
  • void restock(Product *p, int amount) adds a positive amount and ignores anything else
  • const Product *most_valuable(const Product *items, size_t count) returns the line with the highest stock value, or NULL for an empty list
  • Restock the third product by 2, then print every line, the total and the name of the most valuable line
inventory.c
#include <stddef.h>
#include <stdio.h>

typedef struct {
    // TODO: name (char[20]), quantity (int), price (double)
} Product;

double stock_value(const Product *p) {
    // TODO: quantity * price, using ->
}

void restock(Product *p, int amount) {
    // TODO: only add positive amounts
}

const Product *most_valuable(const Product *items, size_t count) {
    // TODO: NULL for an empty list, otherwise a pointer to the best element
}

int main(void) {
    // TODO: an array of 3 products: Notebook 40 x 1.25, Pen 120 x 0.50,
    //       Backpack 3 x 24.00 (try a designated initializer for this one)
    // TODO: restock the backpack by 2, print each line and the total,
    //       then print the most valuable line's name
    return 0;
}

Expected: The output should be: Notebook x 40 = 50.00 Pen x120 = 60.00 Backpack x 5 = 120.00 Total stock value: 230.00 Most valuable line: Backpack

Show hint

printf("%-8s x%3d = %7.2f\n", ...) lines the rows up. In most_valuable, start with const Product *best = &items[0]; and move best whenever stock_value(&items[i]) is larger.

Show solution
inventory.c
#include <stddef.h>
#include <stdio.h>

typedef struct {
    char name[20];
    int quantity;
    double price;
} Product;

double stock_value(const Product *p) {
    return p->quantity * p->price;
}

void restock(Product *p, int amount) {
    if (amount > 0) {
        p->quantity += amount;
    }
}

const Product *most_valuable(const Product *items, size_t count) {
    if (items == NULL || count == 0) {
        return NULL;
    }
    const Product *best = &items[0];
    for (size_t i = 1; i < count; i++) {
        if (stock_value(&items[i]) > stock_value(best)) {
            best = &items[i];
        }
    }
    return best;
}

int main(void) {
    Product shelf[] = {
        {"Notebook", 40, 1.25},
        {"Pen", 120, 0.50},
        {.name = "Backpack", .quantity = 3, .price = 24.00},
    };
    size_t count = sizeof shelf / sizeof shelf[0];

    restock(&shelf[2], 2);
    double total = 0.0;
    for (size_t i = 0; i < count; i++) {
        printf("%-8s x%3d = %7.2f\n", shelf[i].name, shelf[i].quantity,
               stock_value(&shelf[i]));
        total += stock_value(&shelf[i]);
    }
    printf("Total stock value: %.2f\n", total);

    const Product *top = most_valuable(shelf, count);
    if (top != NULL) {
        printf("Most valuable line: %s\n", top->name);
    }
    return 0;
}

Quick quiz 1 / 3

With GCC on x86-64, what is sizeof(struct P) for struct P { char a; double d; char b; };?

Quick quiz 2 / 3

p is a struct Student *. Which expression reads the age?

Quick quiz 3 / 3

a.age is 20. After struct Student b = a; b.age = 30;, what is a.age?

What to remember

  • A struct groups related members of different types into one type; declaring the type reserves no memory.
  • Use . on a struct and -> on a pointer to a struct; p->m means (*p).m.
  • Assignment and pass-by-value copy every member; pass a pointer when a function should modify the original.
  • Padding can make sizeof a struct larger than the sum of its members, so never treat raw struct bytes as a portable format.

SEI CERT C Coding Standard — Carnegie Mellon SEI

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Structures | Thuta Learning