131

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

5
  • 19
    You use a std::vector<int>. And a book. Commented Oct 27, 2010 at 4:32
  • how do you assign and access its data once it's initialized? Commented Nov 30, 2011 at 13:05
  • Have A look at this post, here it is given in detail for every kind of datatypes: programmingtunes.com/dynamic-array-in-c Commented Jul 25, 2014 at 12:44
  • cs.nmsu.edu/~rth/cs/cs471/C%2B%2BDynamicArray.pdf Commented Jun 4, 2020 at 9:40
  • quora.com/What-is-the-meaning-of-%E2%80%9Cint-*p-new-10-%E2%80%9D#:~:text=The%20statement%20defines%20and%20initializes,of%20an%20array%20of%20integers.&text=This%20statement%20will%20dynamically%20allocate,integers%20from%20the%20heap... Commented Jun 4, 2020 at 9:42

8 Answers 8

189
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.

Sign up to request clarification or add additional context in comments.

4 Comments

8 years later that comment might confused beginners @GManNickG, how about deleting it (since I suppose it was made before Jason Iverson actually deleted the array)?
@gsamaras: I agree it's confusing but it's still correct: your code should not have manual deletion that you have to remember not to forget. That is, used smart pointers and other containers.
@GManNickG I think your comment could be less dogmatic. The code is correct, even if it is not ideal. Smart pointers and containers are almost always a better option (especially in a beginner question like this) but not "always" always.
I agree with @Spencer, the code is not wrong, it's simple, perfect c++. You may underlie there's an alternative, call it best practices, etc. But there's nothing wrong about this example per se.
87

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>

1 Comment

I don't know if it's just me but that C++11 syntax looks god awful. The C++14 looks way better. Then again I haven't kept up since pre-C++11. Remembering all these new expression is hard.
38

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

15 Comments

@Ed, the restriction in the question seems rather arbitrary. std::vector with the appropriate constructor works really well and should be pointed out as an alternative. Sometimes people ask the question poorly, and this might count as one of those cases - it's very brief and doesn't give any rationale for preferring new.
@Ed: There's no reason to use new[] instead of std::vector.
@baash: In C++, there's never a reason. If you decide, for whatever reason, to "remove the standard library", you aren't programming in C++ anymore. My comment is for the C++ language, not the C++-language-we-use-on-my-device. Even so, you shouldn't need to delete anything manually, ever. Also, std::vector is a dynamic array, and does nothing with a linked list. It's just a wrapper around a chunk of memory.
@Montdidier: No. You still use new and delete to implement wrappers. The point is you don't manage a resource and use it, you do one or the other.
@Montdidier: Let's start with the claims: In C++, all instances of new[] can be replaced with std::vector. And because std::vector correctly separates resource management from resource usage (SBRM), we should do so.
|
13
int* array = new int[size];

4 Comments

It just answers the question.
@GManNickG Because vector can be more convenient or for other reasons? Because I often encounter 3rd party functions that require the use of arrays instead of vectors.
@Lèsemajesté That's no reason not to use vectors — The std::vector::data() member function will return the underlying raw array when that's needed.
@zenith: Typically, you'd use operator& rather than data() to get a pointer from a vector, but it's true that a vector provides the contiguity guarantee needed for compatibility with functions expecting arrays.
5

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).

Comments

3

dynamically allocate some memory using new:

int* array = new int[SIZE];

2 Comments

You're probably missing the colon, or haven't replaced SIZE with an actual size.
Why should there be a semi-colon? It's not a complete statement. There might be more declarations. This, if included in a complete program, does what the OP asked.
1

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 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) {
        // This approach uses a single array since "new" cannot create 
        // multidimensional arrays.
        // It also spares the performance cost of an array of arrays.
        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++);
            }
        }
    }

2 Comments

Should you use delete[] matrix?
Yeah should be - Adjusted it :)
-7
#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

1 Comment

This has nothing to do with a question about a dynamic array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.