Skip to content

Your own types

Read · 1 of 3

One variable, several fields

struct Student { char name[30]; int roll; int marks; }; describes a new type. struct Student s; makes one, and s.marks is its marks field.

typedef struct { … } Student; lets you write just Student instead of struct Student.

Structs are copied when you assign or pass them, like ints. With a pointer to a struct, use p->marks, which means (*p).marks.

Read this lesson as text

struct bundles a name, a roll number and marks into one value.

One variable, several fields

struct Student { char name[30]; int roll; int marks; }; describes a new type. struct Student s; makes one, and s.marks is its marks field.

typedef struct { … } Student; lets you write just Student instead of struct Student.

Structs are copied when you assign or pass them, like ints. With a pointer to a struct, use p->marks, which means (*p).marks.

Copies again

#include <stdio.h>

typedef struct {
    int x, y;
} Point;

void moveRight(Point p) {
    p.x += 10;
}

void moveUp(Point *p) {
    p->y += 10;
}

int main() {
    Point a = {1, 2};
    moveRight(a);
    moveUp(&a);
    printf("%d %d\n", a.x, a.y);
    return 0;
}

What does this print?

  • 1 12
  • 11 12
  • 11 2
Show the answer

1 12 moveRight changed a copy. moveUp got a's address, so its change to y sticks.

Exercise: A student record

Make a typedef struct called Student with a name (under 30 letters), and three marks.

Read one student as name m1 m2 m3 and print name: total, average with the average to 2 decimals: Asha: 225, 75.00.