0Pricing
C Academy · Lesson

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

  1. Allocating an Array
  2. Growing with realloc
  3. A Reusable Vector Type
  4. Freeing and Avoiding Leaks
← Back to C Academy