🎓 A1Learner
🔍
0 of 50 lessons completed

C Structures

A struct is a group of values that belong together under one name. Each value inside the group is called a member.

One student, three members

A student is built with a name, an age, and a mark. The prints show Ada, 20, and 88.5, so all three members reach the output.

#include <stdio.h>

struct Student {
  char name[20];
  int age;
  float mark;
};

int main() {
  struct Student s1 = {"Ada", 20, 88.5f};
  printf("%s is %d years old.\n", s1.name, s1.age);
  printf("Mark: %.1f\n", s1.mark);
  return 0;
}

Change one member

A student is created, then only the age changes. The prints show Ben is 20 with the same mark, 76.0.

#include <stdio.h>

struct Student {
  char name[20];
  int age;
  float mark;
};

int main() {
  struct Student s1 = {"Ben", 19, 76.0f};
  s1.age = 20;
  printf("%s is %d.\n", s1.name, s1.age);
  printf("Mark: %.1f\n", s1.mark);
  return 0;
}

Copy a whole struct

One student is copied into a second student. The copy prints Cleo, 22, and 91.0, the same values as the first.

#include <stdio.h>

struct Student {
  char name[20];
  int age;
  float mark;
};

int main() {
  struct Student s1 = {"Cleo", 22, 91.0f};
  struct Student s2 = s1;
  printf("%s is %d.\n", s2.name, s2.age);
  printf("Mark: %.1f\n", s2.mark);
  return 0;
}

Example

#include <stdio.h>

struct Book {
  char title[30];
  int pages;
  float price;
};

int main() {
  struct Book b1 = {"C Guide", 240, 19.99f};
  printf("%s\n", b1.title);
  printf("Pages: %d\n", b1.pages);
  printf("Price: %.2f\n", b1.price);
  return 0;
}

Key points

  • A struct groups values of different types under one name.
  • struct Student is a new type built from smaller types.
  • Each member has its own type and its own name.
  • A dot joins the variable name to a member name.
  • s1.age reads the age member of s1.
  • s1.age = 21 gives the age member a new value.
  • A struct can hold a char array, an int, and a float at once.
  • A struct value can be copied into another struct value with =.

A book holds a title, a page count, and a price. The program prints the title first. It then prints the page count and the price.

Note

Code that uses a struct before its definition does not compile.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line reads the age member of a student named s1?