Introduction
A struct groups values that belong together, such as a student's name, ID and CGPA, into one variable.
Keeping a student's name, ID and CGPA in three separate arrays is an accident waiting to happen. A struct lets you group them under one name, and that is the first step towards organising large programs.
How it works
Defining and using a struct
#include <stdio.h>
#include <string.h>
struct student {
char name[12];
int id;
double cgpa;
};
int main(void) {
struct student s;
strcpy(s.name, "Nusrat");
s.id = 2101;
s.cgpa = 3.62;
s.cgpa = s.cgpa + 0.1;
printf("%s (%d): %.2f\n", s.name, s.id, s.cgpa);
return 0;
}struct student { ... }; defines a new type. s.id reads or changes one field with the dot. In the memory panel, a struct shows its fields inside one box, and only the field that changed lights up.
Pointers to structs: ->
When you have a pointer to a struct, p->x means (*p).x: follow the pointer, then take the field. Functions often take a pointer so they can change the struct, or to avoid copying a big one.
Syntax
typedef struct {
int x, y;
} Point;
Point a = {1, 2};
a.x = 5;
Point *p = &a;
p->y = 7;
Example
typedef struct { ... } Point; gives the type a short name, so you can write Point p; instead of struct point p;. An array of structs is like a small table:
#include <stdio.h>
typedef struct {
int x, y;
} Point;
void move(Point *p, int dx, int dy) {
p->x += dx;
p->y += dy;
}
int main(void) {
Point path[3] = {{0, 0}, {2, 1}, {5, 5}};
move(&path[1], 10, 0);
Point copy = path[1];
copy.y = 99;
printf("(%d, %d) and (%d, %d)\n", path[1].x, path[1].y, copy.x, copy.y);
return 0;
}Line by line
Pointis a new type with two fields.movetakes a pointer, so it can change the caller's struct.pathis an array of three points.move(&path[1], 10, 0)changes the second point through its address.Point copy = path[1];copies both fields, so changingcopy.yleavespath[1]alone.
Expected result
(12, 1) and (12, 99)
In the real world
Network packets, file headers and database records are defined as structs. The Linux kernel describes every running program with one very large struct.
Common mistakes
- Forgetting the
;after the closing brace of a struct definition. - Using
.on a pointer (use->), or->on a struct (use.). - Assigning a string field with
=: usestrcpy(s.name, "...").
Best practices
- Group fields that describe one thing.
- Pass large structs by pointer, using
constif they will not change. - Give each struct a clear, singular name.
Summary
A struct groups fields of different types. typedef gives it a shorter name. Assignment copies the whole thing. . reaches a field, and -> reaches a field through a pointer.
Quick check
Key takeaways
- A struct keeps related values together.
- Assigning a struct copies every field.
- Use -> through a pointer and . on a struct.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.