c++ array on heap

To create an array on the heap in C++, follow these steps:

  1. Allocate memory on the heap: Use the new operator to dynamically allocate memory for the array on the heap. The new operator returns a pointer to the first element of the array.

  2. Specify the array type: Declare a pointer variable of the desired array type. For example, if you want to create an array of integers, declare a pointer of type int*.

  3. Assign the allocated memory: Assign the pointer variable with the address returned by the new operator. This links the pointer variable to the allocated memory on the heap.

  4. Access the array elements: Use the pointer variable to access the elements of the array. To access an element at a specific index, use the pointer arithmetic by adding the index to the pointer variable. For example, to access the third element of the array, use *(pointerVariable + 2).

  5. Deallocate memory: After you're done using the array, deallocate the memory on the heap to free up resources. Use the delete[] operator followed by the pointer variable name to deallocate the memory. This prevents memory leaks.

Here's an example that demonstrates these steps:

int* array = new int[5];  // Step 1: Allocate memory for an array of 5 integers

// Step 4: Access the array elements
array[0] = 10;
array[1] = 20;
array[2] = 30;
array[3] = 40;
array[4] = 50;

// Step 5: Deallocate the memory
delete[] array;

This example creates an array of 5 integers on the heap, assigns values to the elements, and then deallocates the memory. Remember to deallocate the memory to avoid memory leaks and potential undefined behavior.