C Structures (structs)
Arrays group many values of the same type. Real-world things, however, are described by values of different types: a book has a title (text), a year (integer) and a price (decimal). A structure (struct) bundles such related values into one new type. Each value inside is called a member (or field).
Defining a structure
struct Book {
char title[50];
int year;
double price;
}; // don't forget this semicolon!This creates a new type named struct Book, but no variable yet. It is a blueprint. To create variables, use the type like any other:
#include <stdio.h>
#include <string.h>
struct Book {
char title[50];
int year;
double price;
};
int main(void) {
struct Book b1;
strcpy(b1.title, "The C Programming Language");
b1.year = 1978;
b1.price = 45.50;
printf("%s (%d) costs %.2f\n", b1.title, b1.year, b1.price);
return 0;
}The C Programming Language (1978) costs 45.50
Members are accessed with the dot operator: variable.member. Note that a char array member is filled with strcpy — you cannot assign a string to an array with =.
Initialising a structure
It is usually easier to give all values when you create the variable. List them in member order, or name them with designated initialisers (C99), which is clearer and order-independent:
#include <stdio.h>
struct Point {
int x;
int y;
};
struct Product {
char name[30];
int stock;
double price;
};
int main(void) {
struct Point origin = {0, 0};
struct Point p = {.y = 7, .x = 3};
struct Product pen = {"Ballpoint pen", 120, 1.25};
struct Product cup = {.name = "Mug", .price = 6.0}; // stock becomes 0
printf("origin = (%d, %d), p = (%d, %d)\n", origin.x, origin.y, p.x, p.y);
printf("%s: %d in stock at %.2f\n", pen.name, pen.stock, pen.price);
printf("%s: %d in stock at %.2f\n", cup.name, cup.stock, cup.price);
return 0;
}origin = (0, 0), p = (3, 7)
Ballpoint pen: 120 in stock at 1.25
Mug: 0 in stock at 6.00
Members not mentioned in an initialiser are set to zero.
Copying structures
Unlike arrays, structures can be assigned with =. All members are copied — including arrays inside the struct — and the copy is independent:
#include <stdio.h>
#include <string.h>
struct Player {
char name[20];
int score;
};
int main(void) {
struct Player a = {"Mia", 300};
struct Player b = a; // full copy
strcpy(b.name, "Noah");
b.score += 50;
printf("a: %s %d\n", a.name, a.score);
printf("b: %s %d\n", b.name, b.score);
return 0;
}a: Mia 300
b: Noah 350
Structures cannot be compared with ==, though; compare the members you care about.
Arrays of structures
An array of structs is the C way of storing a table of records:
#include <stdio.h>
struct City {
const char *name;
int population; // in thousands
double area; // in km^2
};
int main(void) {
struct City cities[] = {
{"Lisbon", 545, 100.0},
{"Vienna", 1982, 414.6},
{"Zurich", 421, 87.9},
};
int n = sizeof(cities) / sizeof(cities[0]);
int biggest = 0;
for (int i = 0; i < n; i++) {
printf("%-7s %5dk people, %6.1f per km^2\n", cities[i].name,
cities[i].population, cities[i].population * 1000 / cities[i].area);
if (cities[i].population > cities[biggest].population) biggest = i;
}
printf("Largest: %s\n", cities[biggest].name);
return 0;
}Lisbon 545k people, 5450.0 per km^2
Vienna 1982k people, 4780.5 per km^2
Zurich 421k people, 4789.5 per km^2
Largest: Vienna
Pointers to structures and ->
Large structures are usually passed to functions by pointer, to avoid copying and to allow modification. With a pointer, members are accessed with the arrow operator ->, which is shorthand for (*ptr).member:
#include <stdio.h>
struct Account {
int id;
double balance;
};
void deposit(struct Account *acc, double amount) {
acc->balance += amount; // same as (*acc).balance += amount
}
void print_account(const struct Account *acc) {
printf("Account %d: %.2f\n", acc->id, acc->balance);
}
int main(void) {
struct Account acc = {1001, 50.0};
deposit(&acc, 25.5);
deposit(&acc, 100.0);
print_account(&acc);
printf("sizeof(struct Account) = %zu bytes\n", sizeof(struct Account));
return 0;
}Account 1001: 175.50
sizeof(struct Account) = 16 bytes
| You have | Access a member with |
|---|---|
a struct variable s |
s.member |
a pointer p to a struct |
p->member (or (*p).member) |
Note:
sizeofa struct can be larger than the sum of its members. The compiler may insert padding bytes so that each member sits at an address suited to its type. Ordering members from largest to smallest often reduces padding.
Test yourself
Which operator accesses a member of a struct variable?
- ->
- .
- ::
- #
If p is a pointer to a struct, how do you access its member score?
- p.score
- p->score
- *p.score
- &p.score
What happens with struct Point b = a; where a is another struct Point?
- Compile error
- b becomes an independent copy of all members
- b points to a
- Only the first member is copied