I am working on a homework assignment and I’m trying to figure out a good way about this.
I want to copy a dynamic array of type say “dog” that contains values from two structs to another “temporary” dynamic array twice the size. Once complete, I want the original array name to replace the “temporary”
pseudo:
user inserts some newnum of elements ->call to func
check if sizeof(array) < (n_items + newnum)
yes: need to grow array
//here's the trouble part
create temp.array 2x sizeof(dog.array), copy dog.array to bigger temp.array
//would i be better off free(dog.array) and then create a new instance of
//dog.array that is now the same size of the temp.array and copy again/free(temp)
//or is there another method to do "new" dog.array = temp.array
When my program checks for room to insert more values into this array, it will go ahead and allocate a new array of twice the size if the first one is full. After this it swaps out the data in a for loop which is fine. I am curious how to go about freeing the old allocated space and then renaming the new “temp” array to match the old ones…or maybe just delete the data associated with the old array, and simply make a pointer of same name to the “temp” one. Not sure how to go about this.
Take a look at the
realloc()function, which lets you change the amount of memory allocated to your pointer of interest. Or you could do amalloc()on a second, distinct pointer,memcpy()bytes from the first pointer to the second, and thenfree()the first pointer. It’s up to you.