C - Pointing to Structures

Overview

Use pointers to structures for efficient passing and to enable dynamic data structures.

Learning Objectives

  • Access struct members through pointers with ->.
  • Allocate and free structs dynamically.

Prerequisites

Example

#include <stdio.h>
#include <stdlib.h>

typedef struct { int x, y; } Point;

int main(void) {
  Point *p = malloc(sizeof *p);
  if (!p) return 1;
  p->x = 3; p->y = 4;
  printf("(%d,%d)\n", p->x, p->y);
  free(p);
}

Common Pitfalls

  • Forgetting to free dynamically allocated structs.
  • Using . instead of -> with pointers.

Checks for Understanding

  1. How do you access member name of Person *p?
Show answer

p->name

Expected Output

(3,4)

Practical Example: Mutate via function

#include <stdio.h>
#include <stdlib.h>

typedef struct { int x, y; } Point;

void translate(Point *p, int dx, int dy) {
  if (p) { p->x += dx; p->y += dy; }
}

int main(void) {
  Point *p = malloc(sizeof *p);
  if (!p) return 1;
  p->x = 1; p->y = 2;
  translate(p, 5, -1);
  printf("(%d,%d)\n", p->x, p->y);
  free(p);
}

Expected Output:

(6,1)

Exercises

  1. Write void scale(Point *p, int factor) to scale a point from origin.
  2. Implement a Rect struct and a function move(Rect *r, int dx, int dy).