Help with c program we are going to expand a standard array

Help with c++ program


we are going to expand a standard array by dynamically allocating a new one with a larger footprint. The program will use a function that accepts an integer array and the size of the integer array, and then increases it to hold one more item. It shifts all of the original array’s values over by one into the new dynamic array, and sets the first element to the value of zero. When the creation and move are complete, this function returns a (smart) unique pointer pointing to the new dynamic array back to the calling program (main).

The program will use the declarations for the array and pointer (in main) as follows:

  const int SIZE = 5;

  int myNumbers[SIZE] = {18, 27, 3, 14, 95};

// Define a unique_ptr smart pointer, pointing

// to a dynamically allocated array of integers.

// A unique_ptr is a small, fast, move-only smart

// pointer usually used for managing resources

// with exclusive ownership semantics

  unique_ptr<int[]> newCopy(new int[SIZE]);

Your program should display 0 18 27 3 14 95after the element shift function does its work.

The Functions (in separate files):

Solution

#include <iostream>
#include <string>

using namespace std;

int* newCopy(int* arr,int n)
{
   int* da=new int[n+1];
   da[0]=0;
   for(int i=1;i<n+1;i++)
   {
       da[i]=arr[i-1];
   }
   return da;
}

void readArr(int* a,int n)
{
   for(int i=0;i<n;i++)
   {
       cout<<a[i]<<\" \";
   }

}

int main(int argc, char const *argv[])
{
   const int SIZE=5;
   int myNumbers[SIZE]={18,27,3,14,95};

   int* unique_ptr;

cout<<\"Old array \"<<endl;
readArr(myNumbers,SIZE);
   unique_ptr=newCopy(myNumbers,SIZE);
cout<<\"\ New array \"<<endl;
readArr(unique_ptr,SIZE+1);
  

   return 0;
}

================================================

output:

akshay@akshay-Inspiron-3537:~/Chegg$ g++ shiftarra.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Old array
18 27 3 14 95
New array
0 18 27 3 14 95

Help with c++ program we are going to expand a standard array by dynamically allocating a new one with a larger footprint. The program will use a function that
Help with c++ program we are going to expand a standard array by dynamically allocating a new one with a larger footprint. The program will use a function that

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site