0

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[]?

5
  • You should use std::vector instead Commented Aug 23, 2019 at 11:20
  • 2
    a[2] = 6; a[3] = 7; will do it. As long as the dimensions don't go out of bounds, you can assign whatever elements you like. Of course, you need some logic to count how many elements of the array are being used. Commented Aug 23, 2019 at 11:27
  • 3
    Did your C++ book get destroyed in a recent house fire? 😪 Commented Aug 23, 2019 at 11:32
  • @LightnessRacesinOrbit hahaha... Good to see humor exists here :D Commented Aug 23, 2019 at 11:35
  • 2
    @RC0993 More than currently present in said house, at least! Commented Aug 23, 2019 at 11:38

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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}

Comments

0

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)

1 Comment

Why copy to a larger one? I assume 100 elements are enough to append two additional values...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.