I’m doing a lot of different things with manipulating arrays without vectors, I was wondering if any one could help me with shifting elements in an array and expanding an array while initializing the new space with elements. I feel like I’m very close to completing this code, but I’m hitting a block.
#include <iostream>
using namespace std;
// Function prototypes
int *reverse(int *, int);
int *expand(int *, int);
int *shift(int *, int);
void display(int[], int);
void display2(int[], int);
void display3(int[], int);
int main()
{
int const SIZE = 5;
int myArray [SIZE] = {1, 2, 3, 4, 5};
int myArray2 [SIZE] = {1, 2, 3, 4, 5};
int myArray3 [SIZE] = {1, 2, 3, 4, 5};
int *arraPtr;
int *arraPtr2;
int *arraPtr3;
arraPtr = reverse(myArray, SIZE);
display(myArray, SIZE);
arraPtr2 = expand(myArray2, SIZE);
display2(myArray2, SIZE);
arraPtr3 = shift(myArray3, SIZE);
display3(myArray3, SIZE);
delete [] arraPtr;
delete [] arraPtr2;
delete [] arraPtr3;
return 0;
}
int *reverse(int *arr, int size)
{
int *copyArray;
int posChange;
if( size < 0)
return NULL;
copyArray = new int[size];
for (int index = 0; index < --size; index++)
{
posChange = arr[index];
arr[index] = arr[size];
arr[size] = posChange;
}
return copyArray;
}
int *expand(int *arr, int size)
{
int *newArray;
newArray = new int[size * 2];
memcpy( newArray, arr, size * sizeof(int));
for (int index = size; index < (size*2); index++)
newArray[index] = 0;
return newArray;
}
int *shift(int *arr, int size)
{
int *newArray;
newArray = arr;
newArray = new int [size + 1];
for (int index = 5; index > 0; index--)
newArray[index] = newArray[index - 1];
return newArray;
}
void display(int arr[], int size)
{
for (int index = 0; index < size; index++)
{
cout << arr[index] << " ";
}
cout << endl;
}
void display2(int arr[], int size)
{
for (int index = 0; index < size; index++)
{
cout << arr[index] << " ";
}
cout << endl;
}
void display3(int arr[], int size)
{
for (int index = 0; index < size; index++)
{
cout <<arr[index] << " ";
}
cout << endl;
}
There are only two compile error:
int newArray;should beint* newArray;and#include <cstring>is missing (necessary formemcpy())Also, the line
display(myArray, SIZE);was probably meant to bedisplay(arraPtr, SIZE);and likewisedisplay2(myArray2, SIZE);— otherwise you’re only displaying the original arrays, not the results of your function calls.However, this could benefit from the safer and more generic C++ algorithms,
std::copy()andstd::reverse_copy()at least:full program: https://ideone.com/RNFiV