0

How can i add a new value to an array?

i want it to be added every time i iterate

17th Aug 2018, 10:16 PM
kenyi lĂłpez
kenyi lĂłpez - avatar
3 Answers
+ 4
Well you can't because arrays work on stack which means their size cannot be changed after compilation. You can use vectors for that, you need to declare vector library then declare a vector like std::vector<dataType> vectorName(Size of vector); initially if you want you can ignore the size of vector and then to enter the value to the vector you write vector_name.push_back(value to be inserted)
17th Aug 2018, 10:43 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 1
You might consider using vectors if you want to expand your array's size. because normal arrays have a constant size. simply do this: #include <vector> ... std::vector<int> vector_of_integers; vector_of_integers.push_back(2); // add value vector_of_integers.pop_back() // remove last pushed value ... also, recommend this video: https://www.youtube.com/watch?v=HcESuwmlHEY&t=486s
18th Aug 2018, 12:23 AM
Light
Light - avatar
0
If you like pure array and not vector or something like that, you can create dynamic array as follows: int *arr = new int[10]; then if you need more values: //pointer to free memory after copying int *tmp = arr; arr = new int[15]; then you can copy old values to new memory that was allocated for your pointer by memcpy(), memmove() or directly within loop.: memcpy(arr, tmp, 10 * sizeof(int)); and finally you can free old memory: delete tmp;
17th Aug 2018, 11:43 PM
Roman Khristoforov
Roman Khristoforov - avatar