The Analogy: A Filing Card With Named Boxes
An array is a row of identical boxes reached by number. A struct is a single filing card with a few named boxes on it, and the boxes may hold different kinds of things — a name, an id, a price.
The card is one object. You hand the whole card to a function, you copy the whole card with one assignment, you keep a drawer of cards. That grouping is the point: an employee is not a name and an id and a salary that happen to be declared near each other, it is one thing with three attributes, and the type system can now say so.
One surprise is worth flagging immediately, because it contradicts what you learned about arrays: structs assign and copy like ordinary values. b = a on two structs duplicates every field. The same line on two arrays does not compile. C treats a struct as a first-class value and an array as an address, and that inconsistency is a genuine wart in the language — but it is one you can exploit, because it makes structs far more pleasant to pass around.
Syntax or Core Structure
#include <stdio.h>
#include <string.h>
struct Point {
int x;
int y;
}; /* the semicolon is required */
struct Employee {
char name[32];
int id;
double salary;
};
int main(void) {
struct Point origin = { 0, 0 };
struct Point p = { .x = 3, .y = 4 }; /* designated, C99 */
struct Employee e = { "Ada Lovelace", 1815, 92500.0 };
printf("origin = (%d, %d)\n", origin.x, origin.y);
printf("p = (%d, %d)\n", p.x, p.y);
printf("employee = %s / %d / %.2f\n", e.name, e.id, e.salary);
struct Point copy = p; /* a real, independent copy */
copy.x = 99;
printf("p.x = %d, copy.x = %d\n", p.x, copy.x);
struct Point *ptr = &p;
printf("via pointer: (%d, %d)\n", ptr->x, ptr->y);
return 0;
}
Output:
origin = (0, 0)
p = (3, 4)
employee = Ada Lovelace / 1815 / 92500.00
p.x = 3, copy.x = 99
via pointer: (3, 4)
copy.x = 99 leaving p.x at 3 proves the assignment was a copy and not an alias.
Dot or arrow
| You have | Write | Equivalent to |
|---|---|---|
a struct value p | p.x | — |
a pointer ptr | ptr->x | (*ptr).x |
The arrow exists purely because *ptr.x would parse as *(ptr.x), which is not what anyone means. The parentheses in (*ptr).x are mandatory, and -> is the readable shorthand nobody should decline.
Initialisation forms
struct Point a = { 3, 4 }; /* positional: order matters */
struct Point b = { .y = 4 }; /* designated: x is zeroed */
struct Point c = { 0 }; /* every member zeroed */
struct Point d; /* indeterminate, all members */
struct Point e = a; /* copy of an existing struct */
Designated initialisers are worth the extra characters: they survive somebody reordering the struct's members, and they document which value means what at the point of use.
Technical Depth: Copying, Comparing and Padding
Structs behave like values, arrays like addresses
| Operation | struct Point | int[2] |
|---|---|---|
b = a | copies both members | does not compile |
| passed to a function | the whole struct is copied | decays to a pointer |
| returned from a function | legal and idiomatic | not possible |
a == b | does not compile | compiles, compares addresses |
sizeof | the whole struct | the whole array, unless it is a parameter |
Two rows there are the ones to remember: a struct can be assigned and returned, and it cannot be compared. There is no member-wise == in C, so equality has to be written out:
int point_equal(struct Point a, struct Point b) {
return a.x == b.x && a.y == b.y;
}
Why memcmp is the wrong way to compare structs
/* Do NOT do this. */
int wrong(const struct Employee *a, const struct Employee *b) {
return memcmp(a, b, sizeof *a) == 0;
}
The compiler inserts unused padding bytes between members to keep each one properly aligned, and the contents of those bytes are indeterminate. Two structs with identical members can differ in their padding, so memcmp reports "different" for values that are equal in every way you care about. Compare member by member, always.
Padding is visible in sizeof
#include <stddef.h>
struct Bad { char a; int b; char c; }; /* sizeof 12 on a typical build */
struct Good { int b; char a; char c; }; /* sizeof 8 on the same build */
With a 4-byte int that must sit on a 4-byte boundary: in Bad, a takes byte 0, bytes 1 to 3 are padding, b occupies 4 to 7, c takes byte 8, and three more bytes of tail padding round the total to 12. In Good, b occupies 0 to 3, a and c take bytes 4 and 5, and two bytes of tail padding give 8. Same three members, two-thirds the size, purely from declaration order.
You can see the layout for yourself with offsetof(struct Bad, b) from <stddef.h>. The practical rule: declare members from largest to smallest when a struct will exist in large numbers, and otherwise order them for readability — a few bytes in a struct you have three of is not worth obscuring the code.
Passing cost
double gross_pay(struct Employee e); /* copies all 48 bytes */
double gross_pay(const struct Employee *e); /* copies 8 bytes */
Passing a small struct by value is fine and often clearer. Passing a large one by value in a loop copies it every call. The convention worth adopting: const T * to read, T * to modify, by value only for small values you want copied anyway — and the const tells the reader which of the three you meant without them checking the body.
The shallow-copy trap
struct Buffer { char *data; size_t len; };
struct Buffer a = { malloc(64), 0 };
struct Buffer b = a; /* copies the POINTER, not the 64 bytes */
free(a.data);
/* b.data is now dangling, and freeing it too is a double free */
Struct assignment copies each member exactly as that member would be copied on its own. A char[32] member is duplicated; a char * member is not — both structs end up pointing at one buffer. Any struct that owns heap memory needs a deliberate copy function and a matching free function, and a comment saying which one of the two structs owns it.
Real World Example: An Inventory Table
An array of structs is the workhorse data structure of C programs: a table of records, functions that search it, and functions that summarise it. Note how the signatures alone tell you which functions can change the data.
#include <stdio.h>
#define MAX_ITEMS 8
struct Item {
int id;
char name[16];
int quantity;
double price;
};
/* Returns a pointer to the match so the caller can modify it, or NULL. */
struct Item *find_item(struct Item *items, size_t n, int id) {
for (size_t i = 0; i < n; i++)
if (items[i].id == id)
return &items[i];
return NULL;
}
/* const: this function reads and cannot alter the table. */
double stock_value(const struct Item *items, size_t n) {
double total = 0.0;
for (size_t i = 0; i < n; i++)
total += items[i].quantity * items[i].price;
return total;
}
void print_table(const struct Item *items, size_t n) {
printf("%3s %-10s %5s %8s %9s\n", "id", "name", "qty", "price", "value");
for (size_t i = 0; i < n; i++)
printf("%3d %-10s %5d %8.2f %9.2f\n",
items[i].id, items[i].name, items[i].quantity,
items[i].price, items[i].quantity * items[i].price);
}
int main(void) {
struct Item stock[MAX_ITEMS] = {
{ 101, "bolt", 250, 0.35 },
{ 102, "nut", 480, 0.20 },
{ 103, "washer", 120, 0.10 },
{ 104, "bracket", 30, 4.75 }
};
size_t count = 4;
print_table(stock, count);
printf("stock value: %.2f\n\n", stock_value(stock, count));
struct Item *washer = find_item(stock, count, 103);
if (washer != NULL) {
washer->quantity += 40; /* modify through the pointer */
printf("received 40 washers -> quantity %d\n", washer->quantity);
printf("stock value: %.2f\n", stock_value(stock, count));
}
if (find_item(stock, count, 999) == NULL)
printf("item 999: not found\n");
return 0;
}
Output:
id name qty price value
101 bolt 250 0.35 87.50
102 nut 480 0.20 96.00
103 washer 120 0.10 12.00
104 bracket 30 4.75 142.50
stock value: 338.00
received 40 washers -> quantity 160
stock value: 342.00
item 999: not found
The forty extra washers add four pounds of stock value, taking 338.00 to 342.00 — check it against the table to confirm the update really went through the array and not through a copy.
Three design points generalise. find_item returns a pointer into the array rather than an index or a copy, which is what lets the caller write washer->quantity += 40 and have it stick; returning a struct Item by value would have handed back a duplicate and the update would have vanished. stock_value takes const struct Item *, so a reader knows at a glance it cannot corrupt the table, and the compiler enforces it. And count is tracked separately from MAX_ITEMS, because the array has capacity 8 but only 4 live records — conflating capacity with count is how programs end up summing uninitialised rows.
One caution about the returned pointer: it is valid only as long as the array is. If stock were heap-allocated and later realloced, every pointer previously returned by find_item would dangle. In that design you return an index instead.
Common Mistakes
- Forgetting the semicolon after the closing brace.
struct Point { int x; int y; }without;produces a cascade of errors on the following lines, which sends people looking in the wrong place.
- Mixing up
.and->.ptr.xon a pointer, orvalue->xon a struct, are both compile errors — mercifully.*ptr.xis the subtler one: it parses as*(ptr.x), so useptr->xor(*ptr).x.
- Comparing structs with
memcmp. Padding bytes are indeterminate, so equal values can compare unequal. Compare member by member.
- Assigning to a char-array member with
=.e.name = "Ada";does not compile, because arrays are not assignable. Usesnprintf(e.name, sizeof e.name, "%s", src).
- Passing a large struct by value in a hot loop. Every call copies every byte. Take
const struct T *when the struct is more than a few words.
- Assuming
sizeofequals the sum of the members. Padding makes it larger, and reordering members can shrink it. Never compute a struct's size by hand.
- Returning a pointer to a local struct. The struct dies when the function returns. Return the struct by value instead — C copies it out for you, which is exactly the case where by-value is right.
- Shallow-copying a struct that owns memory. Assignment duplicates a pointer member, not the buffer behind it, so two structs share one allocation and one of them will free it out from under the other.
Best Practices
- Take
const struct T *to read,struct T *to modify, and pass by value only for small structs you genuinely want copied. The signature then documents the function's intent.
- Use designated initialisers —
{ .id = 101, .quantity = 250 }— so the code survives someone reordering the members, and= { 0 }when you just need a clean slate.
- Keep a separate
countalongside any fixed-capacity array of structs, and never let a loop run to the capacity when only part of it is live.
- Return a pointer into a table when the caller needs to modify the record, and an index when the table can be reallocated or moved.
- Size char-array members from a named constant and fill them with
snprintf, which bounds the write and always terminates.
- Write
initand, if the struct owns anything,freeandcopyfunctions next to the struct definition, and say in a comment which pointer members are owned.
- Order members largest-first when a struct will exist in bulk, and use
offsetofplussizeofto confirm the layout rather than guessing.
- Allocate with
malloc(sizeof *p)so the size tracks the type, andcallocwhen every member should start zeroed.
Practice Exercises
- Prove copy semantics. Define
struct Rect { int w, h; }, create one, copy it with=, modify the copy, and print both. Then definestruct Owner { char *label; }, give it amalloced label, copy it the same way, and print bothlabelpointers with%p. Explain in two sentences why the first copy is safe and the second is a trap.
- Watch padding move. Declare
struct A { char a; int b; char c; };andstruct B { int b; char a; char c; };, printsizeofeach andoffsetoffor all six members. Then add adoubleto both and re-measure. Write down the rule you infer about where the compiler is allowed to place each member.
- Equality, done properly. Write
int item_equal(const struct Item *a, const struct Item *b)that compares all four members correctly, usingstrcmpfor the name. Then write thememcmpversion, and construct twostruct Itemvalues that are equal by your function and unequal bymemcmp— set the members through different code paths so the padding differs.
- Grow the inventory. Add to the example:
int add_item(struct Item *items, size_t *count, size_t capacity, struct Item newItem)that refuses when full and rejects a duplicate id, plusint remove_item(struct Item *items, size_t *count, int id)that removes a record by swapping the last one into the gap. Verify that the stock value after adding two items and removing one matches a figure you calculated by hand.