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.
reallocfunction. Also, you should not cast the result ofmalloc(orrealloc).assertas a method to check for errors from functions, in "release" builds theassertpreprocessor macro does nothing. It might be okay for simple school or book assignments, but using it instead of a properifcheck in real life is a big no-no. Better learn it early to get good habits going from the start.