I'm learning C, specifically OOP in C. As practice, I wrote a dynamically-expanding array.
dynarray.h
#ifndef DYNARRAY_H
#define DYNARRAY_H
typedef struct DynArray {
int length,
capacity,
*arr;
void (*extend)(struct DynArray *dynArr);
void (*insert)(struct DynArray *dynArr, int val);
void (*print) (struct DynArray *dynArr);
} DynArray;
void DynArray_extend(DynArray* dynArr);
void DynArray_insert(DynArray* dynArr, int value);
void DynArray_print(DynArray* dynArr);
#endif
dynarray.c
#include <stdlib.h>
#include "dynarray.h"
DynArray* createDynArray() {
DynArray* newDynArray = malloc(sizeof(DynArray));
newDynArray->capacity = 10;
newDynArray->arr = malloc(sizeof(int)*newDynArray->capacity);
newDynArray->length = 0;
newDynArray->extend = DynArray_extend;
newDynArray->insert = DynArray_insert;
newDynArray->print = DynArray_print;
}
void DynArray_extend(DynArray* dynArr) {
int newCapacity = dynArr->capacity * 2,
*newArr = malloc(sizeof(int)*newCapacity),
i;
dynArr->capacity = newCapacity;
for (i = 0; i < dynArr->length; i++) {
newArr[i] = dynArr->arr[i];
}
}
void DynArray_insert(DynArray* dynArr, int val) {
if (dynArr->length == dynArr->capacity) {
dynArr->extend(dynArr);
}
dynArr->arr[dynArr->length] = val;
dynArr->length = dynArr->length + 1;
}
void DynArray_print(DynArray* dynArr) {
int i;
for (i = 0; i < dynArr->length; i++) {
printf("%d\n", dynArr->arr[i]);
}
}
And this is an example application of the dynamic array (program.c
):
#include <stdio.h>
#include "dynarray.c"
int main( void ) {
int i = 0;
DynArray* someDynArray = createDynArray();
printf("Length : %d\n", someDynArray->length);
printf("Capacity: %d\n", someDynArray->capacity);
for (i = 0; i < 80; i++) {
someDynArray->insert(someDynArray, i);
}
someDynArray->print(someDynArray);
}
I would like to know if there are any flaws in the style of implementing the abstract data type of the dynamically expanding array.