I am trying to implement a dynamic array which must have the following struct:
typedef struct DArray{
void **array;
int capacity;
int size;
void (*display)(FILE *, void *); //function pointer to a non-generic display function
} DArray;
However, with the current behavior, the array doesn't seem to resize, and throws a segfault any time I try to access an index that's not zero. The constructor and insert function is as follows:
DArray *newDArray(void (*d)(FILE *,void *)){
DArray *myDarray = malloc(sizeof(DArray));
myDarray->array = malloc(sizeof(void *)); //size = 1 for now, otherwise multiply by array length
myDarray->capacity = 1;
myDarray->size = 0;
myDarray->display = d;
return myDarray;
}
void insertDArray(DArray *a,void *v){
if (a->size < a->capacity)
a->array[a->size] = v;
else{
void **newArray = malloc(sizeof(void *) * a->capacity * 2); //double size
for (int i = 0; i <= a->size; i++)
newArray[i] = a->array[i]; //clone old array
a->capacity = a->capacity * 2;
free(a->array);
a->array = newArray;
}
a->size++;
}
I'm having trouble understanding my pointers here. I think what's happening is the pointer to a->array still points to the old, unresized array, but doing *a->array = newArray;
does not work either. Can anyone shed some light on this?