Nearby lessons
101 of 124C - Structure Variable
A structure variable is an actual instance of a structure type with real memory. Learn the ways to create one, how to read and write its members, how assignment copies every member, and why sizeof is often larger than you expect.
Three Ways to Create One
Declare after the definition, alongside it, or through a typedef name:
Reading and Writing Members
The dot operator names a member. Each member behaves exactly like an ordinary variable of its type:
An Array Member Is Not Assignable
s.name = "Rahul"; does not compile. A char array member is still an array, so it cannot be assigned after declaration — use strcpy. Curiously, copying the whole structure with b = a; does copy the array, because that is a single struct assignment rather than an array assignment.Assignment Copies Everything
b = a; makes an independent copy of every member. Change b afterwards and a is untouched — the two variables share nothing.The Shallow-Copy Trap
The copy is byte-for-byte. If a member is a pointer, both structures end up pointing at the same memory:
Pointers to Structure Variables
Take the address with & and use -> to reach members. p->x is shorthand for (*p).x:
Why *p.x Does Not Work
The dot binds tighter than *, so *p.x parses as *(p.x) — it tries to dereference the member. The parentheses in (*p).x are mandatory, which is exactly why -> exists:
No == for Structures
Structures cannot be compared as wholes, because padding bytes hold unspecified values. Compare the members you care about:
sizeof and Padding
The compiler inserts unused bytes so each member starts at an address its type likes. That is why the total exceeds the sum:
Arrays of Structure Variables
An array of structures is the standard way to hold many records. Index first, then pick the member:
Common Mistakes
- Using an uninitialised structure — its members hold garbage, exactly like loose local variables.
s.name = "text"— usestrcpyfor array members.p == q— compare member by member instead.*ptr.x— writeptr->xor(*ptr).x.- Using
.on a pointer — the compiler will tell you to use->. - Assuming
sizeofequals the sum of members — padding makes it larger. - Copying a structure with a pointer member — both copies then share one block.
- A definition is the blueprint; a variable is the building.
- Use . on a structure and -> on a pointer to one.
- b = a copies every member, including arrays.
- Structures cannot be compared with == .
- sizeof is usually more than the sum of the members, because of padding.