dynamic arrays c++ code example

Example 1: declare dynamic array c++

int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

Example 2: resizing dynamic array c++

void resize() {
    size_t newSize = size * 2;
    int* newArr = new int[newSize];

    memcpy( newArr, arr, size * sizeof(int) );

    size = newSize;
    delete [] arr;
    arr = newArr;
}

Example 3: how to dynamically allocate an array c++

int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
    a[i] = 0;    // Initialize all elements to zero.
}
. . .  // Use a as a normal array
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.

Example 4: c++ delete dynamically allocated array

int length = 69;
int * numbers = new int[length];
delete[] numbers;

Example 5: dynamic array cpp

#include <iostream>
#include <cstddef> // std::size_t
 
int main()
{
    std::cout << "Enter a positive integer: ";
    std::size_t length{};
    std::cin >> length;
 
    int *array{ new int[length]{} }; // use array new.  Note that length does not need to be constant!
 
    std::cout << "I just allocated an array of integers of length " << length << '\n';
 
    array[0] = 5; // set element 0 to value 5
 
    delete[] array; // use array delete to deallocate array
 
    // we don't need to set array to nullptr/0 here because it's going to go out of scope immediately after this anyway
 
    return 0;
}

Example 6: c++ dynamic array

new T[size]

Tags:

Cpp Example