This is follow up to this one. In the previous some minor errors slipped, so I couldn't update the code. Also took some advice. So final version is below.
header:
#define DEFAULT_CAPACITY 1000
// Define a vector type
typedef struct
{
int nrOfElements; // This just denotes current number of elements.
int capacity; // This denotes the capacity of the array.
int *data; // Actual pointer to array elements.
} CVectorInt;
typedef enum {VECTOR_SUCCESS, VECTOR_OUTOFBOUNDS, VECTOR_MEMORYERROR, VECTOR_LIMITEXCEEDED} vector_status;
vector_status CVectorInit(CVectorInt *vector);
vector_status CVectorAppend(CVectorInt *vector, int value);
vector_status CVectorGet(CVectorInt *vector, int index, int * value);
vector_status CVectorSet(CVectorInt *vector, int index, int value);
void CVectorFree(CVectorInt *vector);
source:
#include "CVectorInt.h"
#include <stdio.h>
#include <stdlib.h>
///
// Initialize vector.
// Set capacity to default value. Current number of elements to 0.
// Allocate memory dynamically for the default number of elements.
//
//
// Return
// If there is some problem, error code is returned.
//
vector_status CVectorInit(CVectorInt *vector)
{
int i = 0;
vector->capacity = DEFAULT_CAPACITY;
vector->nrOfElements = 0;
// Allocate array
vector->data = malloc(sizeof(int) * vector->capacity);
if(vector->data == NULL)
return VECTOR_MEMORYERROR;
// Initialization the array to default values.
for(i = 0; i < DEFAULT_CAPACITY; i++)
vector->data[i] = 0;
return VECTOR_SUCCESS;
}
vector_status CVectorAppend(CVectorInt *vector, int value)
{
int * ptr = NULL;
int i = 0;
if(vector->capacity == 32000)
return VECTOR_LIMITEXCEEDED;
// Do we have room to append elements?
if(vector->capacity <= vector->nrOfElements)
{
// No, increase capacity
vector->capacity *= 2;
// Resize array
ptr = realloc(vector->data, vector->capacity * sizeof(int));
if(ptr == NULL)
{
// We had an error
return VECTOR_MEMORYERROR;
}
else
{
vector->data = ptr;
// Initialize only new elements to 0.
for(i = vector->nrOfElements; i < vector->capacity; i++)
vector->data[i] = 0;
}
}
// Now, after possible resize, add the element.
vector->data[vector->nrOfElements++] = value;
return VECTOR_SUCCESS;
}
vector_status CVectorGet(CVectorInt *vector, int index, int * value)
{
// Is the index within bounds?
if(index < vector->nrOfElements && index >= 0)
{
*value = vector->data[index];
return VECTOR_SUCCESS;
}else
{
return VECTOR_OUTOFBOUNDS;
}
}
vector_status CVectorSet(CVectorInt *vector, int index, int value)
{
// We can't set outside capacity
if(index >= vector->capacity || index < 0)
return VECTOR_OUTOFBOUNDS;
// zero fill the vector up to the desired index
while(vector->nrOfElements <= index)
CVectorAppend(vector, 0);
vector->data[index]=value;
}
void CVectorFree(CVectorInt *vector)
{
// Free underlying array
free(vector->data);
}