I am having problems wrapping my brain around proper use of pointers with arrays in C.
The project I am working on is building a simple Dynamic Array and the functions to go along with it. However I do not seem to be able to find the correct syntax/functions to update the array size dynamically. Here is the relevent code:
Array Creation:
struct DArray
{
TYPE *data; /* pointer to the data array */
int size; /* Number of elements in the array */
int capacity; /* capacity ofthe array */
};
void initDArray(DArray *v, int capacity)
{
assert(capacity > 0);
assert(v!= 0);
v->data = (TYPE *) malloc(sizeof(TYPE) * capacity);
assert(v->data != 0);
v->size = 0;
v->capacity = capacity;
}
DArray* createDArray(int cap)
{
assert(cap > 0);
DArray *r = (DArray *)malloc(sizeof( DArray));
assert(r != 0);
initDArray(r,cap);
return r;
}
And the problem bit, in its current non-working form:
void _DArraySetCapacity(DArray *v, int newCap)
{
TYPE * newptr = createDArray(newCap);
newptr = (TYPE *) malloc(sizeof(TYPE) * newCap);
v->capacity = newCap;
v->data = newptr;
}
My method being to create a temporary pointer with increased memory allocation then copy the existing date to it and point the data pointer at the new location. I suspect I may be looking at the issue in entirely the wrong way.
Any help tips or pointers (pun intended) would be appreciated. Thanks in advance.