How to initialize a dynamic array in C++?


Here is a C++ program to initialize a dynamic array. Here in this program we can use dynamically allocated array to return a local array from the function Array().

Example Code

 Live Demo

#include <iostream>
using namespace std;
int* Array() {
   int* a = new int[100];
   a[0] = 7;
   a[1] = 6;
   a[2] = 4;
   a[3] = 5;
   return a;
}
int main() {
   int* p = Array();
   cout <<"The elements are:"<< p[0] << " " << p[1]<<" " <<p[2] << " " << p[3];
   return 0;
}

Output

The elements are:7 6 4 5

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements