Skip to content
CurriculumChapter 26 ยท Aggregate Types
AdvancedMedium focus~14 min

Structures in Functions & Memory Layout

Structures can be passed and returned by value, but that copies every field. Pointers are cheaper. Layout and padding decide how many bytes a structure really occupies.

In plain English

The compiler packs struct fields like a suitcase. It sometimes leaves gaps so each item starts at a tidy boundary.

01

Passing and returning structures

A function can take a structure by value, which copies the whole object, or by pointer, which copies only the address. Pass by pointer when the function should modify the original or when the structure is large. A function can return a structure by value; the compiler copies it back to the caller. Use a pointer return when the structure is dynamically allocated or owned elsewhere.

chapter-26.cC
struct Point { int x; int y; };

struct Point make_point(int x, int y) {
    struct Point p = {x, y};
    return p;
}

void move_point(struct Point *p, int dx, int dy) {
    p->x += dx;
    p->y += dy;
}
02

Padding, alignment, and sizeof

The compiler may insert padding between members so each member starts at an aligned address. As a result, sizeof(struct) can be larger than the sum of its member sizes. Reordering members can reduce padding. Do not assume a structure is a packed byte-for-byte representation unless you explicitly request packing.

chapter-26.cC
struct Example {
    char c;    /* 1 byte */
    int i;     /* 4 bytes, usually padded to 4-byte alignment */
};

printf("%zu\n", sizeof(struct Example)); /* often 8, not 5 */

Watch it happen

Step through the memory changes one instruction at a time.

step-by-step

Step 1 of 5

Declare struct Example

The compiler lays out the members in declaration order, inserting padding where alignment requires it.

struct Example { char c; int i; };
0c
1pad
2pad
3pad
4i
5i
6i
7i

Key takeaways

  • Passing a structure by value copies all fields.
  • Pass by pointer for mutation or large records.
  • Functions can return structures by value.
  • Padding and alignment make sizeof(struct) larger than the sum of members.

Common pitfalls

  • Assuming struct members are packed tightly.
  • Copying a large structure by value in a hot path.
  • Returning a pointer to a local structure.

Key focus

  • Know why sizeof(struct) may be larger than expected.
  • Choose by-value or by-pointer arguments based on mutation and size.

Quick check

0 / 2 answered

1. Why can sizeof(struct) be larger than the sum of its members?

2. When should you pass a structure by pointer instead of by value?