Lesson 18 of 31

Structs

Structs

A struct groups related variables together into a single type. Each variable inside a struct is called a member or field.

Definition

struct Point {
    int x;
    int y;
};

Starship specifications: hull type, warp capability, crew complement -- all bundled into one struct.

Declaration and Initialization

struct Point p1 = {10, 20};
struct Point p2 = {.x = 30, .y = 40};  // designated initializers

Accessing Members

Use the dot operator .:

printf("(%d, %d)\n", p1.x, p1.y);  // (10, 20)
p1.x = 99;

Structs as Function Parameters

Structs are passed by value (copied) when passed to functions:

void print_point(struct Point p) {
    printf("(%d, %d)\n", p.x, p.y);
}

Returning Structs

Functions can return structs:

struct Point make_point(int x, int y) {
    struct Point p;
    p.x = x;
    p.y = y;
    return p;
}

typedef

You can use typedef to avoid writing struct every time:

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

Point p = {10, 20};  // no need to write "struct"

Your Task

Define a struct Rectangle with int width and int height. Write a function int area(struct Rectangle r) that returns the area. Print the area of a 5x3 rectangle.

TCC compiler loading...
Loading...
Click "Run" to execute your code.