πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English

Structs (struct)

Define structs, access members, combine them with arrays, and use typedef and enum.

πŸ“– What you'll learn on this page
βœ… Must-know essentials
  • struct Point { int x, y; }; groups related fields
  • Access members with p.x
  • Initialize with struct Point p = {3, 4};
⭐ Read if you have time
  • Through a pointer: p->x (same as (*p).x)
  • typedef for a shorter name
  • Nested structs and arrays of structs
πŸ’ͺ Don't worry if it doesn't click right away
Structs themselves are straightforward; the -> operator just requires a grasp of pointers.
How to retry
  1. Start with examples that use only .
  2. Review pointers, then come back
  3. Remember: p->x is shorthand for (*p).x
  4. Use typedef to make names shorter
πŸ’‘ Tip: Rule of thumb β€” use -> through a pointer and . on an object. That covers 90% of cases.

What is a struct?

So far we've declared int, double, and char variables one at a time. But real-world data usually comes as a bundle of related values β€” for example, a person's name, age, and height.
A struct lets you group variables of different types into a single new type.
Without a struct...
char name[20];
int age;
double height;
Add another person and you'll need name1, name2, ... β€” the variable count explodes.
With a struct
struct Person {
  char name[20];
  int age;
  double height;
};
Everything is bundled into a single Person.

Defining and Using a struct

Using a struct takes two steps: (1) define the type (the blueprint), then (2) declare a variable (an instance).
// (1) Define the struct type (blueprint)
struct Student {
  char name[20];
  int score;
};

// (2) Declare variables and use them
struct Student s1;
strcpy(s1.name, "Tanaka");  // access with dot (.)
s1.score = 85;

// You can also initialize at declaration
struct Student s2 = {"Sato", 92};
Access members with the dot operator (.): s1.score means "the score field inside s1."

Struct Memory Layout

Struct members are laid out in memory consecutively, in declaration order.
Memory layout of struct Student s1;
name[20] takes 20 bytes and score takes 4 bytes, so one Student uses at least 24 bytes (padding may add more).

🧱 Padding Visualization β€” member order affects size

For efficient memory access, int needs a 4-byte boundary and double needs an 8-byte boundary (alignment). The compiler inserts padding between members automatically. Just reordering members can shrink a struct.
πŸ§ͺ Pick a pattern
Pick a pattern
// No pattern selected
Size breakdown
Actual data: - B
Padding: - B
sizeof total: - B
β€» Typical values on x86_64 Linux with gcc. Results vary by platform.
Byte-level layout (1 cell = 1 byte)
πŸ’‘ Pro tip: To save memory (embedded systems, huge datasets), declare members from largest to smallest (double β†’ int β†’ short β†’ char). For cache-locality goals, different strategies apply.

Arrays of Structs

An array of structs lets you manage many records that share the same shape. This is where structs really shine.
struct Student class[3] = {
  {"Tanaka", 85},
  {"Sato", 92},
  {"Suzuki", 78}
};

// Print every student's score
for(int i = 0; i < 3; i++){
  printf("%s: %d points\n", class[i].name, class[i].score);
}
Combine the array index with the dot operator, as in class[i].score. It reads naturally as "the i-th student's score."

Passing a struct to a Function

Structs can be passed by value (copied), but copying is expensive for large structs, so passing a pointer is common.
// Pass by value (the struct is copied)
void printStudent(struct Student s){
  printf("%s: %d points\n", s.name, s.score);
}

// Pass by pointer (refers to the original)
void addBonus(struct Student *sp, int bonus){
  sp->score += bonus; // equivalent to (*sp).score
}

addBonus(&s1, 5); // adds 5 points to s1.score
The arrow operator (->) is shorthand for accessing members through a pointer. sp->score is the same as (*sp).score.

typedef β€” Giving a Type an Alias

typedef lets you give a type a clearer alias. It's especially handy with structs.

Basic usage

// An alias for unsigned int
typedef unsigned int uint;
uint score = 100;  // same as unsigned int score = 100;

Structs and typedef (important)

// Without typedef β€” you need "struct" every time
struct Point { int x, y; };
struct Point p1 = {3, 7};  // "struct" required

// With typedef β€” you can drop "struct"
typedef struct { int x, y; } Point;
Point p1 = {3, 7};           // cleaner
In practice, typedef'd structs are the norm. The code is shorter and easier to read.

Enum (enum) β€” A Group of Named Constants

enum lets you name and group related integer constants β€” a great way to avoid magic numbers.
enum Color { RED, GREEN, BLUE };  // RED=0, GREEN=1, BLUE=2

enum Color c = GREEN;
printf("%d\n", c);  // 1

Specifying values

enum Month {
    JAN = 1, FEB, MAR, APR, MAY, JUN,
    JUL, AUG, SEP, OCT, NOV, DEC
}; // FEB=2, MAR=3, ... DEC=12 (auto-incremented)

enum + switch

enum Direction { UP, DOWN, LEFT, RIGHT };

enum Direction dir = UP;
switch (dir) {
    case UP:    printf("Up\n");    break;
    case DOWN:  printf("Down\n");  break;
    case LEFT:  printf("Left\n");  break;
    case RIGHT: printf("Right\n"); break;
}
vs #define: You could write #define RED 0 instead, but an enum is treated as a type, so the compiler can help with type checks.
MethodType checkScopeDebugger display
#define RED 0NoneWhole fileNumber only
enum { RED }YesControllableShown by name

Try It Yourself β€” Structs

Store three students in an array of structs and calculate the average score.
struct.c
Output
Click Run...
πŸ’‘ More ideas to try

Related lessons

Advanced
Pointer Basics
Understand C pointers with memory visualization.
Loops, Arrays, Strings
Arrays
Declaring, initializing, and accessing C arrays.
Advanced
File I/O
fopen, fprintf, fscanf, fclose and how to use them.
← Previous lesson
Lesson 27: Pointer Basics
Next lesson →
Lesson 29: File I/O

Review Quiz

Check your understanding of this lesson.

Q1. Which operator accesses a struct member?

-> (arrow) only
. (dot) only
Both . and -> (depending on context)

Use . (dot) to access directly from a variable, and -> (arrow) to access through a pointer.

Q2. What happens when you pass a struct to a function?

It is passed by reference
A copy of the value is passed
It is a compile error

In C, structs are passed by value (copied). For large structs, passing a pointer is more efficient.

Q3. What does typedef struct do?

Allocates the struct dynamically
Creates an alias for the struct type
Changes the struct's size

typedef creates an alias for a type, letting you write Student s; instead of struct Student s;.

Share this article
Share on X Share on Facebook