Menu

Structs Inside Structs in C: Nesting, Memory and container_of (Linux Kernel Examples)
📰

Structs Inside Structs in C: Nesting, Memory and container_of (Linux Kernel Examples)

DEV Community: beginners·Vadher Nikunj·9 days ago
#PJem0lZ7
#devtobeginners#devto#dev#include#struct
Long article (2095 words) — no AI summary yet.
Reading 0:00
15s threshold

This post was first published on Jupius Learning , where you can read it free with diagrams and practice exercises.

Subscribe to our articles for regular updates .

You can put a struct inside another struct, as a field. The inner struct sits in memory as a block, with its own padding. The outer struct may have padding around that block too. The padding rules from the last post still apply, one level down.

In the first post of this series we declared a struct student , filled it and read it. This time we give that student an address, itself a struct, and we look at how the Linux kernel builds bigger structs out of smaller ones. That includes a small trick called container_of , which takes the address of an inner field and gives you back the outer struct.

All the sizes in this post come from gcc on a 64-bit x86 Linux machine. I compiled and ran every program shown here.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.