C语言结构体的声明与定义:概念辨析及疑问澄清
Great question—this is one of the most common mix-ups when first working with C structs and typedefs, so let’s break this down clearly.
First, let’s correct your initial understanding:
Your line typedef struct { unsigned int counter; } MyStruct; is not just a declaration—it actually combines two key things:
- A definition of an anonymous struct type (we’re telling the compiler exactly what members this struct has, so it knows its size and memory layout)
- A typedef declaration (we’re giving that anonymous struct a shorthand name:
MyStruct)
To get this right, let’s separate the core concepts:
What’s a struct declaration?
A struct declaration only tells the compiler "this struct type exists" without revealing its internal details. The most common example is a forward declaration:
struct MyStruct; // This is a declaration, NOT a definition
At this point, the compiler has no idea what members struct MyStruct has or how big it is. You can use this declaration to create pointers to the struct (struct MyStruct* ptr;), but you can’t define a full variable of this type yet (struct MyStruct obj; would throw an error—compiler can’t allocate memory if it doesn’t know the size).
What’s a struct definition?
A struct definition tells the compiler everything it needs to know about the struct: its members, their types, and thus its total size. This lets the compiler allocate memory for variables of this type. There are two common ways to do this:
- Named struct definition:
Nowstruct MyStruct { unsigned int counter; }; // This is a definitionstruct MyStructis a fully defined type—you can make variables likestruct MyStruct tmpStruct;which allocates memory for the struct instance. - Anonymous struct + typedef (your original example):
Here, we define an unnamed struct, then usetypedef struct { unsigned int counter; } MyStruct;typedefto assign it the aliasMyStruct. NowMyStructacts as a stand-in for that anonymous struct type, soMyStruct tmpStruct;works just like the named version.
What about variable definitions?
Your understanding here is spot-on! Lines like:
MyStruct tmpStruct; // or struct MyStruct tmpStruct;
are variable definitions. This is when the compiler actually sets aside memory for the struct instance. The struct type itself has to be fully defined first (so the compiler knows how much memory to allocate).
Quick recap of your original question
- You were correct that
MyStruct tmpStruct;allocates memory (this is a variable definition). - You were incorrect that
typedef struct { ... } MyStruct;is just a declaration—it’s a struct definition plus a typedef alias.
内容的提问来源于stack exchange,提问作者Lucky

