C Structures
A structure (struct) groups multiple related variables of possibly different types under one name. This is useful for representing real-world entities like a person, point, or record with several fields.
Unlike arrays, a structure's members can have different types, and each member is accessed using the dot (.) operator on a struct variable.
struct Name {
type member1;
type member2;
};Defining and using a struct
You define a struct with the `struct` keyword and a block of member declarations. You then create variables of that struct type and access members with the dot operator.
Structs and pointers
When you have a pointer to a struct, use the arrow operator -> instead of dot to access members, which is shorthand for dereferencing then accessing the member.
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p = {3, 4};
printf("%d,%d\n", p.x, p.y);
return 0;
}3,4The struct Point groups x and y, accessed with the dot operator.
#include <stdio.h>
struct Point { int x; int y; };
void printPoint(struct Point *p) {
printf("%d,%d\n", p->x, p->y);
}
int main() {
struct Point p = {1, 2};
printPoint(&p);
return 0;
}1,2The arrow operator -> accesses struct members through a pointer.
Key points
- A struct groups related variables of possibly different types.
- Members are accessed with the dot (.) operator on a struct variable.
- The arrow (->) operator accesses members through a struct pointer.
- Structs can be passed to functions by value or by pointer.
