Structs
Group related fields with typedef and pass by pointer for mutation.
Code
#include <stdio.h>
#include <string.h>
typedef struct {
char name[32];
int age;
float gpa;
} Student;
// Pass by pointer to avoid copying and allow mutation
void birthday(Student *s) {
s->age++;
}
void print_student(const Student *s) {
printf("%-10s age=%d gpa=%.2f\n", s->name, s->age, s->gpa);
}
int main(void) {
Student a;
strncpy(a.name, "Alice", sizeof(a.name) - 1);
a.name[sizeof(a.name) - 1] = '\0';
a.age = 20;
a.gpa = 3.7f;
Student b = {"Bob", 22, 3.5f};
print_student(&a);
birthday(&a);
print_student(&a);
print_student(&b);
return 0;
}Explanation
A struct groups related fields of different types into one named unit, and typedef gives that type a short alias. The arrow operator -> accesses fields through a pointer, while the dot operator accesses them directly. Passing structs by pointer avoids copying large values and lets functions modify the caller's data.
More C Snippets
Pointer Basics
Declare pointers, dereference, and walk an array with pointer arithmetic.
Memory Management
Allocate, resize, and free heap memory with malloc, realloc, and free.
String Operations
Use string.h helpers for length, copy, concat, compare, and tokenize.
File I/O
Open, read, write, and close files using the stdio FILE API.
Function Pointers
Store function addresses for callbacks and dispatch tables.
Preprocessor Macros
Define object-like and function-like macros with conditional compilation.