As homework, I have to write a function that changes an array's size using malloc and free functions only.
I know how to do it with realloc, but I don't know how to do it with malloc.
typedef struct{
int *tab;
int size;
}arr;
and I need to write this function :
void changeSizeDyn(arr *Dyn_arr, int size){
//
}
As mentioned in the homework: it requires only one reallocation and only one memory release, and only one copy of the elements from the old array.
I searched a lot but only found results using realloc.
Is it even possible to do that without using realloc?
Let's say you allocated the array like this initially:
You should realloc it with this function:
Which should be called this way:
You can use this function even for the first allocation (although you should set to
NULLand0both values first). You also don't need to add a free; an input of 0 would do it for you, just likereallocwould do:If you pass a structure where
dyn_arr->nmembis already a negative value (shouldn't happen), the behaviour is undefined (that negative value would go intomemcpy, which would be wrapped into a very highsize_t, which would overflow the arrays). I didn't want to check for that because it would be unnecessary in any non-buggy scenario.