C: Advanced Structures

🗓 Last updated: 2026-11-30👤 Written by: Ivy✓ Reviewed by: Dana🏷 Category: C Tutorial

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).

Reference entries in this section: const typedef struct sizeof _Alignas

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:

TEXT
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;
}
💡 Tip: Returning a small struct by value is fine. For large structs, pass a pointer and fill it to avoid copy overhead.

(2) Filling a Struct Through a Pointer

C
// 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:

TEXT
void print_student(const struct Student *s) {
    printf("%s %d %.1f\n", s->name, s->age, s->score);
}
⚠️ Note: 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

C
// 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;
💡 Tip: No need to write struct Student anymore — just use Student directly.

(2) typedef with Struct Pointers

TEXT
typedef struct Node {
    int data;
    struct Node *next;
} Node, *NodePtr;

Node n1 = {10, NULL};
NodePtr head = &n1;
⚠️ Note: When a struct references itself, you must still use struct Node *next because the alias isn't in effect yet at that point.

(3) Other Uses of typedef

C
// 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
TEXT
<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

  1. Each member's offset must be a multiple of that member's size
  2. The total size of the struct must be a multiple of the largest member's size
C
// 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;
};
TEXT
printf("%zu\n", sizeof(struct Align1));
printf("%zu\n", sizeof(struct Align2));
TEXT
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.

💡 Tip: Grouping smaller members together reduces padding bytes — a practical technique for saving memory.

(2) #pragma pack

You can specify the alignment boundary to compress a struct:

C
// 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));
TEXT
6
⚠️ Note: Packed alignment reduces access efficiency and can even cause errors on some platforms. Only use it in scenarios that strictly require byte alignment, such as protocol parsing or file format handling.


4. Bit-Fields

Bit-fields allocate space to members on a bit-by-bit basis, saving memory.

C
// 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;
};
C
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));
TEXT
ready=1 error=0 mode=5 count=1024
Struct size: 8
⚠️ Note: Bit-field layout is compiler-dependent and not portable. You cannot take the address of a bit-field member (&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.

C
// Type definition
typedef struct {
    // Variable declaration
    int len;
    int data[];
} IntVec;

When using it, allocate extra space as needed:

C
// 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);
TEXT
0 100 200 300 400
💡 Tip: Flexible array members are commonly used to implement variable-length structs. Compared to using a pointer to separate memory, the data is contiguous and a single free suffices.

⚠️ Note: The flexible array must be the last member, and the struct must have at least one other member. You cannot use sizeof to get the size of a flexible array.

▶ Example 2: Structure Padding Demonstration

▶ Try it Yourself

输出:

TEXT
sizeof(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

输出:

TEXT
sizeof(Flags) = 4 byte(s)
read=1 write=0 execute=1

Reference entries in this section: const typedef struct sizeof _Alignas

❓ FAQ

Q What is the difference between typedef and #define for type aliases?
A typedef is a compiler-level type alias that respects scope rules, handles pointer types correctly (e.g., 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.
Q Why does memory alignment exist?
A CPUs read memory more efficiently at aligned boundaries, and some architectures (ARM, SPARC) fault on unaligned access. The compiler automatically inserts padding between members to align each member to its natural boundary (e.g., 4-byte ints on 4-byte boundaries). This is not "waste" — it is a hardware requirement.
Q What is structure padding in C?
A Structure padding is the automatic insertion of unused bytes between struct members so each member sits at its natural alignment boundary. A struct with a char followed by an int may have 3 padding bytes. The total sizeof reflects the padding, not just the member sizes. Use offsetof() from stddef.h to inspect exact member offsets.
Q How do I avoid structure padding?
A Two approaches. First, reorder members from largest to smallest alignment requirement (e.g., double before int before char) — this minimizes padding without tricks. Second, use #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.
Q What is pragma pack in C?
A #pragma pack(n) tells the compiler to use n-byte alignment for struct members. pragma pack(1) gives byte alignment (no padding). It is a non-standard compiler extension (GCC, MSVC, Clang all support it) and should be paired with #pragma pack() to restore default alignment. The standard C equivalent is _Alignas (C11).
Q What is a bit field in C?
A A bit field lets you declare an integer member that occupies a specific number of bits inside a struct: 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.
Q What is a flexible array member?
A A flexible array member (C99+), written as 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.
Q Why should we typedef a struct so often in C?
A Because in C you must write 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

📝 Exercises

  1. Define a struct containing char, short, int, and double. Try two different member orderings and use sizeof to verify the size difference
  2. Use typedef to define a linked list node type, then write functions to create and traverse a singly linked list
  3. Use a flexible array member to implement a dynamic string struct (with len and data[]), supporting an append-character operation
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏