Dynamic Memory Allocation Example on C++

Updated: Apr 22, 2020

#include <iostream>

using namespace std;

int *create_array(size_t size, int init_value = 0) {
 int *new_storage {nullptr};
   new_storage = new int[size];   
 for (size_t i{0}; i < size; ++i)
      *(new_storage + i) = init_value;
 return new_storage;

void display(const int *const array, size_t size) {
 for (size_t i{0}; i < size; ++i)
        cout << array[i] << " ";
    cout << endl;
int main() {
 int *my_array {nullptr};
 size_t size;
 int init_value {};
    cout << "\nHow many integers would you like to allocate? ";
    cin >> size;
    cout << "What value would you like them initialized to? ";
    cin >> init_value;
    my_array = create_array(size, init_value);
    cout << "\n--------------------------------------" << endl;

 display(my_array, size);
 delete [] my_array;
 return 0;

Recent Posts

See All

Dijkstra shortest path algorithm

Word ladder game (change only one letter to go from Fool to Sage): Fool, Pool, Poll, Pole, Pale, Sale, Sage. How? Dijkstra shortest path algorithm

Deep Learning for Algorithmic Trading

Finance is highly nonlinear and sometimes stock price data can even seem completely random. Machine learning and Deep Learning have found their place in the financial institutions for their power in p

Statistical Arbitrage Trading Pairs

What are z score values? A Z score is the value of a supposedly normal random variable when we subtract the mean and divide by the standard deviation, thus scaling it to the standard normal distributi

©2020 by Arturo Devesa.