Reputation:
How to add element to last of array in c++?
int a[100] = {4,5}
How to add 6 to a[], then add 7 to a[]?
Upvotes: 0
Views: 1646
Reputation: 15501
You have an array of 100 elements initialized by an initializer list {4, 5}
. This means a[0]
is initialized to 4
, a[1]
is initialized to 5
and all other array elements are initialized to 0
. Just because there are two elements in the initializer list doesn't mean there is an end of array after the second element. There are 98 more array elements, all set to the value of 0
. Your array size is fixed. It's 100 elements. If you want a container that dynamically changes its size, use std::vector instead.
Upvotes: 4
Reputation:
Your using a C-style array which are fixed size, so either just replace the value at the next index - or use std::vector
which is dynamic size (https://en.cppreference.com/w/cpp/container/vector)
Upvotes: 0
Reputation: 27567
Looks like, as mentioned in the comments, you're looking for a std::vector
:
std::vector<int> a{4, 5};
a.push_back(6); // a now {4, 5, 6}
a.push_back(7); // a now {4, 5, 6, 7}
Upvotes: 2