C Structs: Custom Data Structures
C Structures (structs)
A struct is a user-defined data type in C that allows you to group together elements of different data types under a single name, facilitating the creation of records.
Member Access:
- Use dot (
.) for standard struct variables. - Use arrow (
->) when accessing struct members through a pointer.
Structures in memory are laid out sequentially, but compilers may insert padding bytes between members to align them with hardware boundaries, affecting the structure's total size.
To save memory and increase performance, you can use the typedef keyword to define clean aliases for structures, and pass pointers to structures instead of copying large records by value.
Typedef Aliases
The typedef keyword lets you declare user-friendly names for struct objects, allowing you to instantiate points or records without repeating the struct keyword.
c
#include <stdio.h>
typedef struct { int x, y; } Point;
int main() {
Point p1 = {10, 20};
Point *ptr = &p1;
printf("Coords: %d, %d\n", ptr->x, ptr->y);
return 0;
}
c
#include <stdio.h>
#include <string.h>
struct Book {
char title[50];
int pages;
};
int main() {
struct Book b1;
strcpy(b1.title, "C Programming");
b1.pages = 280;
printf("Book: %s (%d pages)\n", b1.title, b1.pages);
return 0;
}