C Language | Structure Declarations | Structure Members

Structures can contain other structures and pointers to structures. These features make it possible to build complex data models.

Structures Containing Structures

struct Point { int x, y; };
struct Size { int width, height; };
struct Rectangle {
 struct Point location;
 struct Size size;
};

Access nested members from the outer structure inward.

rect.size.width
rect->size.width

Code 1

#include <stdio.h>

struct Point { int x, y; };
struct Size { int width, height; };
struct Rectangle { struct Point location; struct Size size; };

int main() {
 struct Rectangle rect = { 100, 50, 400, 300 };
 printf("Location (%d, %d): Size (%d, %d)\n",
   rect.location.x, rect.location.y, rect.size.width, rect.size.height);
 return 0;
}

Self-Referential Structures

A structure cannot directly contain an instance of itself because its size would never be complete.

struct Node { struct Node node; }; /* invalid */

It can contain a pointer to the same type.

struct Node { struct Node *next; };

This pattern is useful for linked lists and trees.

Code 2

#include <stdio.h>

struct Chain {
 char *text;
 struct Chain *next;
};

void ShowChain(struct Chain *chain) {
 if (chain == NULL) return;
 printf("%s\n", chain->text);
 ShowChain(chain->next);
}

int main() {
 struct Chain first = { "First Chain", NULL };
 struct Chain second = { "Second Chain", NULL };
 first.next = &second;
 ShowChain(&first);
 return 0;
}