98

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

Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
Sudantha
  • 13,722
  • 39
  • 100
  • 152
  • 14
    You use a `std::vector`. And [a book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – GManNickG Oct 27 '10 at 04:32
  • how do you assign and access its data once it's initialized? –  Nov 30 '11 at 13:05
  • Have A look at this post, here it is given in detail for every kind of datatypes: http://programmingtunes.com/dynamic-array-in-c/ – user2808359 Jul 25 '14 at 12:44
  • https://www.cs.nmsu.edu/~rth/cs/cs471/C%2B%2BDynamicArray.pdf – Nagappa Jun 04 '20 at 09:40
  • https://www.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... – Nagappa Jun 04 '20 at 09:42

7 Answers7

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

Jason Iverson
  • 2,100
  • 1
  • 12
  • 15
  • 31
    I won't -1, but if you can even possibly forget to `delete`, your code is wrong. – GManNickG Oct 27 '10 at 04:32
  • 3
    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 Oct 06 '18 at 15:00
  • 3
    @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 Oct 06 '18 at 16:40
  • 5
    @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. – Spencer Apr 10 '20 at 16:03
  • 6
    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. – Arman Dec 03 '20 at 09:15
69

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>

Ben Voigt
  • 260,885
  • 36
  • 380
  • 671
  • 2
    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. – Keya Kersting Apr 09 '20 at 20:59
33

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
jveazey
  • 5,190
  • 1
  • 27
  • 43
  • 8
    @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`. – Mark Ransom Oct 27 '10 at 04:23
  • 4
    @Ed: There's no reason to use `new[]` instead of `std::vector`. – GManNickG Oct 27 '10 at 04:33
  • Gman.. On windows ce devices STL is huge.. You take a big hit for using it. Actually that would hold true for several embedded devices, where an extra meg on your app means your user gets hours less use between data dumps. – baash05 Oct 27 '10 at 04:52
  • Oh.. also.. I believe STL uses a combination of linked list and array to accomplish the vector. The memory limits of embedded devices would take a hit in that respect too. NOTE: There is never a reason to say never a reason :) There are two reasons in as many minutes :) – baash05 Oct 27 '10 at 04:55
  • 3
    @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. – GManNickG Oct 27 '10 at 05:01
  • I'm not saying my device.. I'm saying that SLT is a bit expensive. And that though it's a standard c++, it's not always practical on all platforms. You never create anything dynamically? If you do, how do you get rid of it.. (I learn every day) – baash05 Oct 27 '10 at 05:44
  • @GMan: Following your argument I could equally say - Using new and delete is part of the C++ language and not using it is not programming in C++. Surely it just depends on what you want to achieve? – Montdidier Oct 27 '10 at 05:48
  • 1
    @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. – GManNickG Oct 27 '10 at 05:50
  • @GMan: I assume you're talking about separation of concerns in a design? Otherwise I'm not sure what you're talking about. – Montdidier Oct 27 '10 at 06:27
  • 2
    @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. – GManNickG Oct 27 '10 at 06:35
  • Sorry about that. No idea where my head was. I should have provided an example. – jveazey Oct 27 '10 at 07:17
  • 1
    Ok, point was, show him how to do what he has asked, and then suggest better alternatives. The fact that you should be using std::vector does not mean you shouldn't understand how the rest of the language works. – Ed S. Oct 27 '10 at 17:21
  • @GManNickG there is one great reasons to use `new[]` instead of `std::vector` when you dont what to initialize primitive type array, e.g. `unsigned char[]`. For example, when you want to allocate bytes array to store network packet to receive, and you dont want to initialize each byte in array before receiving packet for performance. To avoid `delete[]`, you can use smart pointers like `std::unique_ptr`. You could say std::vector with custom allocator to avoid initialization, but that needs learning and more code than `std::unique_ptr`. – nullptr Nov 29 '19 at 05:40
  • @nullptr for network packets, would you not want to use well defined structs and load directly into them? Then, it's just a variable and doesn't require allocations using new[]. Or read directly into streams, where you can validate the contents as you extract from the stream? – jveazey Dec 01 '19 at 21:40
  • @jveazey depends on complexity. For example MPEG-TS packet, will not be easy design struct or parse correctly. Also `reinterpret_cast`ing array to struct pointer may be better when further content depends on previous content in packet – nullptr Dec 05 '19 at 10:29
7
int* array = new int[size];
Ed S.
  • 115,705
  • 20
  • 165
  • 244
  • 3
    It just answers the question. – Ed S. Oct 27 '10 at 17:20
  • @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èse majesté Dec 19 '14 at 02:40
  • 5
    @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. – emlai Jun 22 '15 at 18:54
  • 3
    @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. – Ben Voigt Jun 22 '15 at 20:11
3

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

carimus
  • 133
  • 7
1

dynamically allocate some memory using new:

int* array = new int[SIZE];
SCBuergel
  • 1,394
  • 14
  • 23
Montdidier
  • 1,111
  • 1
  • 8
  • 20
  • 2
    You're probably missing the colon, or haven't replaced SIZE with an *actual* size. – Montdidier Oct 27 '10 at 04:08
  • 5
    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. – Benjamin Lindley Oct 27 '10 at 04:29
-1
#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