C: Advanced Structures
Advanced structs are like decorating a house — it's not just about building a frame, but also about efficient space usage (alignment), saving materials (bit-fields), and flexible expansion (flexible arrays).
1. Advanced Struct Usage with Functions
(1) Functions That Return a Struct
C allows functions to return a struct directly — the compiler handles the copying:
struct Point make_point(int x, int y) {
struct Point p = {x, y};
return p;
}
int main(void) {
struct Point pt = make_point(3, 4);
printf("(%d, %d)\n", pt.x, pt.y);
return 0;
}
(2) Filling a Struct Through a Pointer
// Function definition
void fill_student(struct Student *s, const char *name, int age, float score) {
strncpy(s->name, name, 19);
s->name[19] = '\0';
s->age = age;
s->score = score;
}
// Function definition
int main(void) {
struct Student stu;
fill_student(&stu, "Alice", 20, 88.5);
// Return result
return 0;
}
(3) const Protection for Struct Parameters
To prevent a function from modifying a struct, use const on the pointer parameter:
void print_student(const struct Student *s) {
printf("%s %d %.1f\n", s->name, s->age, s->score);
}
const struct Student *s means you cannot modify the pointed-to struct through s, but s itself can point to something else.
2. typedef for Type Aliases
typedef creates an alias for a type, reducing the need to repeatedly write the struct keyword.
(1) Basic Usage
// Type definition
typedef struct {
char name[20];
// Variable declaration
int age;
// Variable declaration
float score;
} Student;
Student s1 = {"Alice", 20, 89.5};
Student *ps = &s1;
struct Student anymore — just use Student directly.
(2) typedef with Struct Pointers
typedef struct Node {
int data;
struct Node *next;
} Node, *NodePtr;
Node n1 = {10, NULL};
NodePtr head = &n1;
struct Node *next because the alias isn't in effect yet at that point.
(3) Other Uses of typedef
// Type definition
typedef unsigned char Byte;
// Type definition
typedef int (*Comparator)(const void *, const void *);
Byte flag = 0xFF;
Comparator cmp = my_compare;
▶ Example
▶ Try it Yourself<C Programming> 320 pages $59.00
<C Programming> 320 pages $47.20
3. Struct Memory Alignment
Struct members are not tightly packed in memory — the compiler inserts padding bytes according to alignment rules.
(1) Alignment Rules
- Each member's offset must be a multiple of that member's size
- The total size of the struct must be a multiple of the largest member's size
// Struct/enum/union definition
struct Align1 {
// Variable declaration
char a;
// Variable declaration
int b;
// Variable declaration
char c;
};
// Struct/enum/union definition
struct Align2 {
// Variable declaration
char a;
// Variable declaration
char c;
// Variable declaration
int b;
};
printf("%zu\n", sizeof(struct Align1));
printf("%zu\n", sizeof(struct Align2));
12
8
Layout of Align1: a (1 byte) + 3 bytes padding + b (4 bytes) + c (1 byte) + 3 bytes padding = 12.
Layout of Align2: a (1 byte) + c (1 byte) + 2 bytes padding + b (4 bytes) = 8.
(2) #pragma pack
You can specify the alignment boundary to compress a struct:
// Preprocessor directive
#pragma pack(push, 1)
// Struct/enum/union definition
struct Packed {
// Variable declaration
char a;
// Variable declaration
int b;
// Variable declaration
char c;
};
// Preprocessor directive
#pragma pack(pop)
// I/O operation
printf("%zu\n", sizeof(struct Packed));
6
4. Bit-Fields
Bit-fields allocate space to members on a bit-by-bit basis, saving memory.
// Struct/enum/union definition
struct Flags {
unsigned int ready : 1;
unsigned int error : 1;
unsigned int mode : 3;
unsigned int : 0;
unsigned int count : 12;
};
readyoccupies 1 bit (0 or 1)erroroccupies 1 bitmodeoccupies 3 bits (0-7): 0forces alignment to the next storage unitcountoccupies 12 bits
struct Flags f = {1, 0, 5, 1024};
// I/O operation
printf("ready=%u error=%u mode=%u count=%u\n", f.ready, f.error, f.mode, f.count);
// I/O operation
printf("Struct size: %zu\n", sizeof(f));
ready=1 error=0 mode=5 count=1024
Struct size: 8
&f.ready is illegal).
5. Flexible Array Members
C99 allows the last member of a struct to be an array of length 0, called a Flexible Array Member.
// Type definition
typedef struct {
// Variable declaration
int len;
int data[];
} IntVec;
When using it, allocate extra space as needed:
// Variable declaration
int n = 5;
IntVec *v = (IntVec *)malloc(sizeof(IntVec) + sizeof(int) * n);
v->len = n;
// For loop
for (int i = 0; i < n; i++) {
v->data[i] = i * 100;
}
// For loop
for (int i = 0; i < v->len; i++) {
// I/O operation
printf("%d ", v->data[i]);
}
// Dynamic memory operation
free(v);
0 100 200 300 400
sizeof to get the size of a flexible array.
▶ Example 2: Structure Padding Demonstration
▶ Try it Yourself输出:
TEXTsizeof(WithoutPack) = 12 sizeof(WithPack) = 7 offsetof(b) in WithoutPack = 4 offsetof(b) in WithPack = 1
▶ Example 3: Bit Fields for Compact Storage
▶ Try it Yourself输出:
TEXTsizeof(Flags) = 4 byte(s) read=1 write=0 execute=1
❓ FAQ
typedef int *intptr; makes intptr a pointer type), and is visible in debuggers. #define is a preprocessor text substitution with no type information — prefer typedef for actual type aliases.#pragma pack(1) before the struct and #pragma pack() after, which forces byte alignment. pragma pack reduces CPU access efficiency and is non-standard — use it only for protocol parsing or file format structs.#pragma pack() to restore default alignment. The standard C equivalent is _Alignas (C11).unsigned flags: 3;. Bit fields pack tightly, reducing memory use when you have many boolean-like flags. Limitations: cannot take the address of a bit field, cannot use sizeof on individual fields, and layout is implementation-defined.int data[] at the end of a struct with one other member before it, lets you allocate a struct plus variable-length data in one malloc call. The flexible array has zero size in sizeof but contributes to malloc calculation. It is superior to a pointer member because you avoid two allocations and two frees.struct Student every time unless you typedef it. typedef struct Student Student lets you write just Student. This is purely syntactic sugar — C++ removed the need, but C still requires explicit struct qualification without typedef.📖 Summary
- Functions can return structs; for large structs, prefer filling through a pointer for efficiency
typedefcreates type aliases, simplifying struct type names- Structs have memory alignment — member ordering affects total size
#pragma packcan override alignment rules, useful for protocol parsing and similar scenarios- Bit-fields allocate space bit by bit, saving memory but are non-addressable and non-portable
- Flexible array members enable variable-length structs with contiguous data and simple allocation/deallocation
📝 Exercises
- Define a struct containing char, short, int, and double. Try two different member orderings and use sizeof to verify the size difference
- Use typedef to define a linked list node type, then write functions to create and traverse a singly linked list
- Use a flexible array member to implement a dynamic string struct (with len and data[]), supporting an append-character operation