C ยท Chapter 30 of 45

C Structures

A structure (struct) groups multiple related variables of possibly different types under one name. This is useful for representing real-world entities like a person, point, or record with several fields.

Unlike arrays, a structure's members can have different types, and each member is accessed using the dot (.) operator on a struct variable.

Syntax
struct Name {
  type member1;
  type member2;
};

Defining and using a struct

You define a struct with the `struct` keyword and a block of member declarations. You then create variables of that struct type and access members with the dot operator.

Structs and pointers

When you have a pointer to a struct, use the arrow operator -> instead of dot to access members, which is shorthand for dereferencing then accessing the member.

Example 1 (c)
#include <stdio.h>

struct Point {
  int x;
  int y;
};

int main() {
  struct Point p = {3, 4};
  printf("%d,%d\n", p.x, p.y);
  return 0;
}
Output
3,4

The struct Point groups x and y, accessed with the dot operator.

Example 2 (c)
#include <stdio.h>

struct Point { int x; int y; };

void printPoint(struct Point *p) {
  printf("%d,%d\n", p->x, p->y);
}

int main() {
  struct Point p = {1, 2};
  printPoint(&p);
  return 0;
}
Output
1,2

The arrow operator -> accesses struct members through a pointer.

Key points

  • A struct groups related variables of possibly different types.
  • Members are accessed with the dot (.) operator on a struct variable.
  • The arrow (->) operator accesses members through a struct pointer.
  • Structs can be passed to functions by value or by pointer.
๐Ÿ’ก Note: Passing large structs by pointer avoids the overhead of copying every member each time.

๐Ÿ“ Quick Quiz

1. What does a struct group together?

2. Which operator accesses a struct member from a variable directly?

3. Which operator accesses a struct member through a pointer?