C++ Array shifter using pointers Write a function that accepts an int array and
ID: 3777000 • Letter: C
Question
C++ Array shifter using pointers
Write a function that accepts an int array and the array’s size as arguments. The function should create a new array that is one element larger than the argument array. The argument array and size is user defined in main(), hence, use dynamic memory allocation. The first element of the new array should be set to 0. Element 0 of the argument array should be copied to element 1 of the new array, element 1 of the argument array should be copied to element 2 of the new array, and so forth. This process needs to be done by using pointer notation rather than array notation/indexing. The function should return a pointer to the new array. Display the original array and the newly shifted array from the main()
Explanation / Answer
#include <iostream>
using namespace std;
int* shift(int*, int);
int main()
{
const int SIZE = 10; //Number of elements
int ary [SIZE] = {1, 2, 3, 4, 1, 6, 7, 12, 9, 10}; //Used to hold numbers
int* num = ary;
for(int index= 0;index<SIZE;index++)
cout<<num[index]<<endl;
num =shift(ary, SIZE); //Used to assign num to the memory location of the return
for(int index=0;index<SIZE;index++)
cout<<num[index]<<endl;
num = 0; //Used to point the unused elements of the second array with zero.
return 0;
}
int* shift(int* arr, int size)
{
int new_size = size + 1;
int* shifter = new int[new_size];
shifter[0] = 0;
for(int i = 0; i < size; ++i)
{
shifter[i + 1] = arr[i];
}
arr = shifter;
//return expandSize;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.