I have answered a Question in Stackoverflow link.
a) Create a function called resize that can be used to increase the size of integer arrays dynamically. The function takes three parameters. The first parameter is the original array, the second parameter is the size of this array, and the third parameter is the size of the larger array to be created by this function. Make sure that you allocate memory from the heap inside this function. After allocating memory for the second array the function must copy the elements from the first array into the larger array. Finally, the function must return a pointer to the new array.
b. In main, allocate an array on the heap that is just large enough to store the integers 5, 7, 3, and 1.
c. Resize the array to store 10 integers by calling the resize function created in step a. Remove the old (smaller) array from the heap. Add the numbers 4, 2, and 8 to the end of the new array.
d. Write a sort function that sorts any integer array in increasing order.
e. Use the sort function to sort the array of numbers in c above. Display the sorted numbers.
Is there a Dangling pointer issue.
#include <array>
#include <iostream>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
//Bubble Sort
bool sort(int arr[], int size)
{
for( int i = 0; i< size -1; i++)
{
for( int j = 0; j < size - i -1; j++)
{
//descending order
if(arr[j]<arr[j+1])
{
swap(&arr[j], &arr[j+1]);
}
}
}
return true;
}
void Print(int Array[], int nSize)
{
for( int i = 0; i < nSize; i++)
{
std::cout<<" "<<Array[i];
}
std::cout<<"\n";
}
void Resize( int *&Array, const int& nSizeOld, const int& nSize )
{
int * newArray = new int[nSize];
//Copy Elements of the Array
for(int i = 0; i< nSize; i++)
{
newArray[i] = Array[i];
}
delete[] Array;
//Assign ptr of Prev to new Array
Array = newArray;
}
int _tmain(int argc, _TCHAR* argv[])
{
const int kNewSize = 10, kSize = 5;
int *pMyArray = new int[kSize];
//Set Values
for( int i = 0; i< kSize; ++i )
{
pMyArray[i] = i * 5;
}
Resize( pMyArray, kSize, kNewSize );
//Set Values
for( int i = kSize; i< kNewSize; ++i )
{
pMyArray[i] = i * 10;
}
Print(pMyArray, kNewSize);
sort(pMyArray, kNewSize);
Print(pMyArray, kNewSize);
if( pMyArray!=NULL )
{
delete[] pMyArray;
}
return 0;
}
std::vector
instead. That said, if you do need/want to implement your own low level array resizing, you should be usingstd::realloc()
. The reference page I linked to even provides some (to my inexpert eye) decent example code. \$\endgroup\$