C Language | Structure Declarations | Pointers to Structures

Structures have addresses and can be accessed through pointers.

Indirectly Accessing Structure Members

Declare a pointer to a structure like this:

struct Point *pointer = &pt;

Dereference the pointer before using the member access operator.

int x = (*pointer).x;
#include <stdio.h>

struct Point {
  int x;
  int y;
};

int main(void) {
  struct Point pt = { 100, 200 };
  struct Point *ppt = &pt;
  printf("pt.x = %d : pt.y = %d\n", (*ppt).x, (*ppt).y);
  return 0;
}

The arrow operator provides a shorter equivalent form.

pointer->member

pointer->member means the same as (*pointer).member.

printf("pt.x = %d : pt.y = %d\n", ppt->x, ppt->y);

Pointers are commonly used to pass structures to functions without copying the entire value.

struct Point {
  int x;
  int y;
};

void SizeToPoint(struct Point *offsetPoint, struct Point *target,
                 int width, int height) {
  target->x = offsetPoint->x + width;
  target->y = offsetPoint->y + height;
}

The caller passes structure addresses, and the function writes the calculated coordinates through target. The return value remains available for reporting success or failure if needed.