I would like to write a function (changeSize) that uses DMA, where I can choose to change it's (an array's) size to whatever I want, where oldEls is the original size, and newEls is the new size. If newEls is larger than oldEls, I would just add zero's to the end, and if it is smaller than oldEls, I would just truncate. The "ptr" parameter needs to point to the new array. It is my understanding that this would be similar to the C realloc() function.
With the code presently below, I am outputting the following: 0, 0, 3, 6, 0, 0, 0, 0, where the correct output should be 4, 2, 3, 6, 0, 0, 0, 0. I also realize that my show function is maybe not the best function to output the new array, since I have to explicit state the array element size.
Thanks in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
void show( const int a[], unsigned elements );
int * copy( const int a[], unsigned els );
void changeSize( int * & ptr, int newEls, int oldEls );
void die(const string & msg);
int main()
{
int arr[4] = {4, 2, 3, 6};
show(arr, 4);
int * newArr = copy(arr, 4);
cout << endl << endl;
changeSize(newArr, 8, 4);
show(newArr, 8);
}
void show( const int a[], unsigned elements )
{
for (int i = 0; i < elements; i++)
cout << a[i] << endl;
}
int * copy( const int a[], unsigned els )
{
int *newArr;
try
{
newArr = new int[els];
}
catch(const bad_alloc &)
{
die("Copy: Alloc Failure");
}
for (int i = 0; i < els; i++)
newArr[i] = a[i];
return newArr;
}
void changeSize( int * & ptr, int newEls, int oldEls )
{
int * newArr;
try
{
newArr = new int[newEls];
for (int i = 0; i < oldEls; i++)
{
newArr[i] = ptr[i];
}
if (newEls > oldEls)
{
for (int k = oldEls; k < newEls; k++)
newArr[k] = 0;
}
}
catch(const bad_alloc &)
{
die("changeSize: Alloc Failure");
}
ptr = newArr;
delete[] newArr;
}
void die(const string & msg)
{
cerr << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
First of, you call delete on
newArrat the end ofchangeSize. you need to delete the old value of ptr (that you currently discard). That's (probably) the problemWhile I'm at it, I'd like to point your interest to
std::vector. It's basically a resizeable array.Also, copying raw chucks of memory is still best done with
memcpy, don't waste your time with writing for loops just to copyints, do that only for C++ classes.EDIT: using
std::copyis the best solution for C++, it usesmemcpywhen it can, otherwise it's the same as a for loop copying the objects.Cheers!