Dynamic memory allocation in C++

To run a C++ program:

The example of using dynamic memory allocation


#include <iostream>
#include <stdlib.h> // need this to use malloc
using namespace std;

int main () {
  int n, i;
  int * numbers;

  cout << "Please enter a number: ";
  cin >> n;

  // allocate memory for n integers:
  numbers = (int *) malloc(n * sizeof(int));

  for (i = 0; i < n; ++i) {
    numbers[i] = i;

  }

  for (i = 0; i < n; ++i) {
    cout << numbers[i] << " ";
  }

  cout << endl;
  // free the memory at the end
  free(numbers);

}

CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.