C Structures
C structures, written with the struct keyword, group variables of different types under one name. A struct is perfect for representing a real thing, such as a student with a name, age and GPA.
Defining and Using a Struct
#include <stdio.h>
struct Student {
char name[30];
int age;
double gpa;
};
int main(void) {
struct Student s = {"Ayesha", 21, 3.8};
printf("%s, %d, GPA %.1f\n", s.name, s.age, s.gpa);
s.age = 22;
printf("New age: %d\n", s.age);
return 0;
}Ayesha, 21, GPA 3.8 New age: 22
typedef and Designated Initializers
typedef gives the struct a shorter name so you can skip the struct keyword. Designated initializers set members by name.
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
int main(void) {
Point p = {.y = 8, .x = 3};
printf("(%d, %d)\n", p.x, p.y);
return 0;
}(3, 8)
Pointers to Structs and the Arrow Operator
When you have a pointer to a struct, use -> to access members. p->x is short for (*p).x. Passing a pointer avoids copying a large struct and lets the function modify it.
#include <stdio.h>
typedef struct {
char owner[20];
double balance;
} Account;
void deposit(Account *acc, double amount) {
acc->balance += amount;
}
int main(void) {
Account a = {"Bilal", 100.0};
deposit(&a, 50.0);
printf("%s: %.2f\n", a.owner, a.balance);
return 0;
}Bilal: 150.00
Arrays of Structures
#include <stdio.h>
typedef struct {
const char *name;
int qty;
} Item;
int main(void) {
Item cart[] = {{"Rice", 2}, {"Tea", 1}, {"Oil", 3}};
for (int i = 0; i < 3; i++) {
printf("%-5s x%d\n", cart[i].name, cart[i].qty);
}
return 0;
}Rice x2 Tea x1 Oil x3
Frequently asked questions
What is the difference between . and -> in C?
Use the dot operator with a struct variable (s.age) and the arrow operator with a pointer to a struct (p->age).
Why use typedef with struct in C?
typedef creates an alias so you can write Point p instead of struct Point p. It makes code shorter and easier to read.
Can a struct contain another struct in C?
Yes. Members can be any type, including other structs, arrays and pointers. Access nested members with chained dots, like order.customer.name.