Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "int_vector.h"
- struct IntVector *newIntVector(int capacity)
- {
- struct IntVector *vector = malloc(sizeof(struct IntVector));
- if(capacity <= 0) return NULL;
- vector->data = malloc(capacity * sizeof(int));
- vector->size = 0;
- vector->capacity = capacity;
- return vector;
- }
- void freeIntVector(struct IntVector *vector)
- {
- free(vector->data);
- vector->data = NULL;
- vector->size = 0;
- vector->capacity = 0;
- }
- void pushIntVector(struct IntVector *vector, int value)
- {
- if(vector->size < vector->capacity)
- {
- vector->data[vector->size++] = value;
- }
- else // reallocate internal buffer
- {
- int *buffer = malloc(2 * sizeof(int) * vector->capacity);
- memcpy(buffer, vector->data, sizeof(int) * vector->size);
- free(vector->data);
- vector->data = buffer;
- vector->capacity *= 2;
- vector->data[vector->size++] = value;
- }
- }
- bool popIntVector(struct IntVector *vector)
- {
- if(vector->size > 0)
- {
- vector->size--;
- return true;
- }
- return false;
- }
- int *getIntVector(struct IntVector *vector, int index)
- {
- if(index < 0 || index >= vector->size)
- return NULL;
- return &vector->data[index];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement