How to create a dynamic array of integers

C++

C++ Problem Overview


How to create a dynamic array of integers in C++ using the new keyword?

C++ Solutions


Solution 1 - C++

int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

Don't forget to delete every array you allocate with new.

Solution 2 - C++

Since C++11, there's a safe alternative to new[] and delete[] which is zero-overhead unlike std::vector:

std::unique_ptr<int[]> array(new int[size]);

In C++14:

auto array = std::make_unique<int[]>(size);

Both of the above rely on the same header file, #include <memory>

Solution 3 - C++

You might want to consider using the Standard Template Library . It's simple and easy to use, plus you don't have to worry about memory allocations.

http://www.cplusplus.com/reference/stl/vector/vector/

int size = 5;                    // declare the size of the vector
vector<int> myvector(size, 0);   // create a vector to hold "size" int's
                                 // all initialized to zero
myvector[0] = 1234;              // assign values like a c++ array

Solution 4 - C++

int* array = new int[size];

Solution 5 - C++

As soon as question is about dynamic array you may want not just to create array with variable size, but also to change it's size during runtime. Here is an example with memcpy, you can use memcpy_s or std::copy as well. Depending on compiler, <memory.h> or <string.h> may be required. When using this functions you allocate new memory region, copy values of original memory regions to it and then release them.

//    create desired array dynamically
size_t length;
length = 100; //for example
int *array = new int[length];

//   now let's change is's size - e.g. add 50 new elements
size_t added = 50;
int *added_array = new int[added];

/*   
somehow set values to given arrays
*/ 

//    add elements to array
int* temp = new int[length + added];
memcpy(temp, array, length * sizeof(int));
memcpy(temp + length, added_array, added * sizeof(int));
delete[] array;
array = temp;

You may use constant 4 instead of sizeof(int).

Solution 6 - C++

dynamically allocate some memory using new:

int* array = new int[SIZE];

Solution 7 - C++

The answers above are all good for assigning one-dimensional int-arrays. Anyhow, I want to add that it is also possible to do this for multi-dimensional arrays you'd normally define like int[][] matrix = {{1,2}, {3,4}}.

The key is that you dynamically store all elements in one array and make use of the fact that the array is a continuous block in memory (see here for a clarification of "block"), meaning that you can "slice" yourself through dimensions. Below you can see an example for a 2d-array.

You can find a discussion regarding this topic here on SO.

/*Defining a 2d-matrix.*/
struct Matrix {

    int rows, columns;
    int* matrix;

    Matrix(int rows, int columns) : rows(rows), columns(columns) {
        // Keep in mind that arrays cannot be generated during runtime
        // since the compiler needs to know the size to allocate in memory.
        // Thus, use dynamic memory and keep in mind to delete it!

        // This only uses a single array since "new" cannot create 
        // multidimensional arrays by default. Thus, everything is
        // written in a single memory-block and accessed via getElement().
        matrix = new int[columns * rows];
    }

    ~Matrix() {
        // Release the memory after destroying the Matrix-object
        delete matrix;
    }

    /*Access the element at position [r]ow and [c]olumn.*/
    int getElement(int r, int c) {
        // matrix[c][r] is rewritten as matrix[column + columns * rows] 
        // -> matrix <=> Single memory block
        return matrix[c + columns * r];
    }

    /*Set the element at position [r]ow and [c]olumn with given [val]ue.*/
    void setElement(int r, int c, int val) {
        matrix[c + columns * r] = val;
    }
};

An example to populate such a Matrix-object would be:

    /*Initialize the matrix with the continuous numbers 0..N*/
    void Matrix::initDummyMatrix(){
        int counter = 0;
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < columns; ++col) {
                setElement(row, col, counter++);
            }
        }
    }

Solution 8 - C++

#include <stdio.h>
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    
    float arr[2095879];
    long k,i;
    char ch[100];
    k=0;

    do{
        cin>>ch;
        arr[k]=atof(ch);
        k++;
     }while(ch[0]=='0');
    
    cout<<"Array output"<<endl;
    for(i=0;i<k;i++){
        cout<<arr[i]<<endl;
    }
    
    return 0;
}

The above code works, the maximum float or int array size that could be defined was with size 2095879, and exit condition would be non zero beginning input number

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSudantha View Question on Stackoverflow
Solution 1 - C++Jason IversonView Answer on Stackoverflow
Solution 2 - C++Ben VoigtView Answer on Stackoverflow
Solution 3 - C++jveazeyView Answer on Stackoverflow
Solution 4 - C++Ed S.View Answer on Stackoverflow
Solution 5 - C++carimusView Answer on Stackoverflow
Solution 6 - C++MontdidierView Answer on Stackoverflow
Solution 7 - C++MarkusView Answer on Stackoverflow
Solution 8 - C++shawndfernandesView Answer on Stackoverflow