C++ problem. Write only the function not the whole program Write a function that
ID: 3581408 • Letter: C
Question
C++ problem.
Write only the function not the whole program
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 that the argument array. The first element of the new array should be set to 0. Element 0 of the argument array should be cpoied to element 1 of the new array, element 1 of the argument should be copied to element 2 of the new array and so forth. The function should return a pointer to the new array.
Explanation / Answer
#include <iostream>
using namespace std;
int* createArray(int a[], int size){
int *pvalue = NULL;
pvalue = new int;
*pvalue = size+1;
const int n = *pvalue;
int *b = 0;
b = new int[n];
b[0] = 0;
for(int i=0; i<size; i++){
b[i+1] = a[i];
}
return b;
}
int main()
{
int a[] = {2,3,1,5,4};
int *b = createArray(a, 5);
cout<<"New array elemeents are: "<<endl;
for(int i=0; i<6; i++){
cout<<*(b+i)<<" ";
}
cout<<endl;
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
New array elemeents are:
0 2 3 1 5 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.