A Reusable Vector Type
Wrap size and capacity.
From Loose Code to a Type
Passing around a pointer, a count, and a capacity as three separate variables is error-prone.
Let's bundle them into one struct: a reusable dynamic array, often called a vector. It packages the data and the bookkeeping together.
The Vector Struct
A vector needs three fields: a pointer to the data, how many elements are used (len), and how many fit before resizing (cap).
typedef struct {
int *data;
size_t len;
size_t cap;
} Vec;All lessons in this course
- Allocating an Array
- Growing with realloc
- A Reusable Vector Type
- Freeing and Avoiding Leaks