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) .
carimus Dec 31 '15 at 10:33 2015-12-31 10:33
source share