patterncMinor
Dynamically-expanding array in C
Viewed 0 times
arraydynamicallyexpanding
Problem
I'm learning C, specifically OOP in C. As practice, I wrote a dynamically-expanding array.
dynarray.h
dynarray.c
And this is an example application of the dynamic array (
I would like to know if there are any flaws in the style of implementing th
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);
#endifdynarray.c
#include
#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 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 length; i++) {
printf("%d\n", dynArr->arr[i]);
}
}And this is an example application of the dynamic array (
program.c):#include
#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 insert(someDynArray, i);
}
someDynArray->print(someDynArray);
}I would like to know if there are any flaws in the style of implementing th
Solution
My 2 cents:
- I believe
createDynArrayshould return something.
- The returned value of
createDynArraymight have a special value ofNULLin case that one of themallocs calls failed (this scenario should be covered by the code).
- In the implementation of extend - consider using
reallocinstead ofmallocand manual copy. If you insist onmallocperhaps usingmemcpymight be more elegant than a manual copy.
- I'd move magic numbers to
#defines: Initial Capacity (hard-coded to 10) and Growth Factor (2). Alternatively, they could be parameters to thecreateDynArrayfunction
- How would you free this struct? Perhaps you should add a "destructor" to be called before calling
freewith the struct pointer as a parameter.
- In terms of functionality, other than printing this "array", how would the consuming programmer could get (or set) a specific item in this "array"?
Context
StackExchange Code Review Q#15819, answer score: 6
Revisions (0)
No revisions yet.