Write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate. The function should return a pointer to the array. Call the function in a complete program.

Respuesta :

Answer:

#include <iostream>

#include <cstdlib>

using namespace std;

int* integerArr( int number);

int main(){

   int* address;

   address = integerArr(5);

   for ( int i = 0; i < 10; i++ ) {

     cout << "Address of the integer array:  ";

     cout << *(address + i) << endl;

   }

   return 0;

}

int* integerArr( int number){

   int myArr[number];

   for (int i = 0; i < number; ++i) {

     myArr[i] = rand();

   }

   int* ptr= myArr;

   return ptr;

}

Explanation:

The C++ source calls the defined pointer function "integerArr" with an integer argument to declare arrays of dynamic length, in the main function of the program and the items of the array are printed on the screen.