C Workshop · Structures
Foundation C

Structures

A struct groups related fields under one name. p.x and p.y belong together.

What it is

A struct is a bundle of related fields under one name. A point is not two lonely ints; it is x and y that belong together. You reach a field with a dot: p.x.

Approach

  1. Define the struct type.
  2. Declare a variable of that type.
  3. Set each field, then print them.

Where this is used in the real world

Diagram

1

Point

type

2

p.x=3

field

3

p.y=4

field

4

print

3 4

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2struct Point {
3    int x;
4    int y;
5};
6int main(void) {
7    struct Point p;
8    p.x = 3;
9    p.y = 4;
10    printf("%d %d\n", p.x, p.y);
11    return 0;
12}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. p.x is:

Dot.

2. This lesson prints:

Both fields.

3. Fields of a struct:

Group related data.

4. q->x is used when q is:

Arrow.

5. typedef struct Point Point lets you write:

Shorter type name.