How to create a dynamic array of integers

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

+44
c ++
Oct 27 '10 at 4:01
source share
6 answers
 int main() { int size; std::cin >> size; int *array = new int[size]; delete [] array; return 0; } 

Remember to delete every array that you allocate with new .

+73
Oct 27 2018-10-10T00:
source share
— -

Since C ++ 11, there is a safe alternative to new[] and delete[] , which has zero load 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 a single header file, #include <memory>

+33
Apr 24 '15 at 18:55
source share

You might want to use the standard template library. It is simple and easy to use, plus you do not need to worry about memory allocation.

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 
+19
Oct 27 '10 at 4:12
source share
 int* array = new int[size]; 
+4
Oct. 27 '10 at 4:09
source share

As soon as the question arises about a dynamic array, you can not only create an array with a variable size, but also change its size at runtime. Here is an example with memcpy , you can use memcpy_s or std::copy . Depending on the compiler, <memory.h> or <string.h> may be required. When using these functions, you select a new memory area, copy the original memory areas into it, and then release them.

 // create desired array dynamically size_t length; length = 100; //for example int *array = new int[length]; // now let change is size - eg 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 can use constant 4 instead of sizeof(int) .

+3
Dec 31 '15 at 10:33
source share

dynamically allocate some memory with new :

 int* array = new int[SIZE]; 
0
Oct. 27 '10 at 4:04 on
source share



All Articles