A common approach to implementing a resizable array (“vector” or “ArrayList”) in C is to create a structure that maintains:
A pointer to a dynamically allocated block of elements.
The current number of elements stored (the “size”).
The current allocated capacity (the “capacity”) of the block.
When inserting a new element, if the size reaches the capacity, you reallocate (typically doubling the capacity) so you have room for more elements.
Below is an example implementation for a vector of integers. You can adapt the idea to work with other types (using void* pointers and proper casting, or by using macros/templates in C).
Step-by-Step Implementation
Define the structure:
The structure holds a pointer to the data, the current number of elements (size), and the maximum number of elements that can be stored before resizing (capacity).
c
typedef struct {
int *data; // Pointer to the array of integers.
size_t size; // Number of elements currently in the vector.
size_t capacity; // Allocated capacity of the vector.
} Vector;
Initialize the Vector:
Write a function to initialize the vector with an initial capacity. It allocates memory for the data and sets the size to 0.
c
#include <stdlib.h>
#include <stdio.h>
// Initial capacity one can tune as needed
#define INITIAL_CAPACITY 4
void vector_init(Vector *v) {
v->size = 0;
v->capacity = INITIAL_CAPACITY;
v->data = malloc(v->capacity * sizeof(int));
if (v->data == NULL) {
fprintf(stderr, "Failed to allocate memory for vector.\n");
exit(1);
}
}
Resize the Vector:
Create a function that doubles the capacity when needed. This is usually done in the insertion function but can also be a separate function.
c
void vector_resize(Vector *v, size_t new_capacity) {
int *new_data = realloc(v->data, new_capacity * sizeof(int));
if (new_data == NULL) {
fprintf(stderr, "Failed to reallocate memory for vector.\n");
exit(1);
}
v->data = new_data;
v->capacity = new_capacity;
}
Push (Add) an Element:
Check if resizing is needed before inserting, then add the element.
c
void vector_push_back(Vector *v, int value) {
if (v->size == v->capacity) {
// Double the capacity
vector_resize(v, v->capacity * 2);
}
v->data[v->size] = value;
v->size++;
}
Access Elements:
You might provide a function to get an element at a given index. Here is a simple version with bounds checking:
c
int vector_get(Vector *v, size_t index) {
if (index >= v->size) {
fprintf(stderr, "Index out of bounds.\n");
exit(1);
}
return v->data[index];
}
Free the Vector:
When done using the vector, free the allocated memory.
Here’s a complete example putting it all together:
c
#include <stdio.h>
#include <stdlib.h>
#define INITIAL_CAPACITY 4
typedef struct {
int *data;
size_t size;
size_t capacity;
} Vector;
void vector_init(Vector *v) {
v->size = 0;
v->capacity = INITIAL_CAPACITY;
v->data = malloc(v->capacity * sizeof(int));
if (v->data == NULL) {
fprintf(stderr, "Failed to allocate memory for vector.\n");
exit(1);
}
}
void vector_resize(Vector *v, size_t new_capacity) {
int *new_data = realloc(v->data, new_capacity * sizeof(int));
if (new_data == NULL) {
fprintf(stderr, "Failed to reallocate memory for vector.\n");
exit(1);
}
v->data = new_data;
v->capacity = new_capacity;
}
void vector_push_back(Vector *v, int value) {
if (v->size == v->capacity) {
vector_resize(v, v->capacity * 2);
}
v->data[v->size] = value;
v->size++;
}
int vector_get(Vector *v, size_t index) {
if (index >= v->size) {
fprintf(stderr, "Index %zu out of bounds (size: %zu).\n", index, v->size);
exit(1);
}
return v->data[index];
}
void vector_free(Vector *v) {
free(v->data);
v->data = NULL;
v->size = 0;
v->capacity = 0;
}
int main() {
Vector v;
vector_init(&v);
// Add elements to the vector
for (int i = 0; i < 10; i++) {
vector_push_back(&v, i * 10);
}
// Access and print elements
for (size_t i = 0; i < v.size; i++) {
printf("v[%zu] = %d\n", i, vector_get(&v, i));
}
vector_free(&v);
return 0;
}
Explanation
Dynamic Allocation:
The vector’s data pointer holds an array of integers allocated dynamically.
Resizing Strategy:
When the vector’s size equals its capacity, we double the capacity with realloc. Doubling is a common strategy that makes the amortized cost of insertion constant.
Error Checking:
Always check the result of malloc and realloc to avoid issues when memory allocation fails.
Memory Management:
When done with the vector, call vector_free to release the allocated memory and avoid memory leaks.
Generality:
This example is for integers. For a generic vector, you could use a void* pointer and store the size of each element (using sizeof(type)) in the vector structure. You’d then cast the pointer appropriately when accessing elements.
Conclusion
You now have a simple implementation of a vector/arraylist in C. This basic example can be expanded with more functionalities (such as inserting at arbitrary positions, deleting elements, etc.) and adapted to handle generic data types if needed.