So I'm trying to create a function that "resizes" a member array to a new size passed as an argument. By "resize", I mean that it should set the member array to a new array with the new size, copy over the elements from the old array, and then deallocate the memory associated with the old array. Here's what I have so far:
void MemoryTest::resize(unsigned int new_size) {
if (size == new_size)
return;
int* oldPtr = elements;
elements = new int[new_size + 1];
for (int i = 0; i < (new_size < size) ? new_size : size; i++)
elements[i] = oldPtr[i];
elements[new_size] = '\0';
if (size > new_size)
size = new_size;
delete[] oldPtr; // Deallocate old elements array
}
elements is a private member int* initialized to NULL.
However, when it begins the for loop, the program hangs for awhile before giving an Access Violation for the elements[i] = oldPtr[i] line. Someone please correct me if I'm wrong (which I probably am), but my understanding is that oldPtr should be a pointer pointing to the same initial point as elements. Then, I set elements equal to a new array, so the two are now pointing to two different things. Then I iterate through elements, setting each item equal to its counterpart in the old array.
Also, while I would normally use a vector to avoid situations like this, I'm trying to become more familiar with pointers and memory allocation in C++.
Thanks in advance!
sizeis not accurate after the first call to this function. I can't determine if it's accurate before.sizewill be wrong when the array is made larger.I'm trying to make size reflect the number of elements, not the number of memory spots in the array,That's why vector has bothsizeandcapacitymembers.