C Programming

Lesson 2 of 11

Structs

C has no classes, but it has structs: a way to group related variables together under one name.

C

.x and .y are the struct's members, accessed with the dot operator, each one assigned separately here. Some C compilers also support initializer syntax like struct Point p = { .x = 3, .y = 4 }; (a designated initializer, setting each member by name in one go), but this course sticks to plain assignment since it's supported more consistently everywhere, including the interpreter running these examples.

Memory layout

A struct isn't magic, it's just its members laid out contiguously in memory, one right after another, in declaration order (the compiler may add small gaps called padding for alignment, but conceptually think of it as one solid block):

C

This matters a lot once pointers enter the picture: a pointer to a struct is just an address pointing at the start of that block, and every member is at a fixed, predictable offset from it.

typedef

Writing struct Point everywhere gets tedious, typedef gives it a shorter alias:

C

Now Point can be used on its own, exactly like a built-in type such as int.

📝 Structs Quiz

Passing score: 70%
  1. 1.How are a struct's members arranged in memory?

  2. 2.typedef creates a shorter alias for a type, like naming an anonymous struct Point instead of writing struct Point every time.

  3. 3.Given "struct Point p;", you access its x member with the ____ operator: p.x