vectors with no size | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

vectors with no size

I don't know why the vector just only let me input 9 numbers. Can someone explain pls? #include <iostream> using namespace std; int main(){ int i=-1, size=1, *vector=new int[size]; do{ i++; size++; cin>>vector[i]; }while(vector[i]); return 0; }

2nd Jan 2020, 4:30 PM
javier mateos manzano
javier mateos manzano - avatar
3 Answers
+ 2
I think there's one thing you need to know: Just because you increment value of "size" it doesn't mean size of vector is increased, so what you do is, you create vector for 1 element, then you add some values to it, where actually you are doing it outside of reserved memory area, so behaviour there is undefined. BTW I do not understand the while condition. What was the idea behind it?
2nd Jan 2020, 5:20 PM
Jakub Stasiak
Jakub Stasiak - avatar
+ 1
Well I figured out that size++ don't increase the size, and while the number is not 0, the while should work, and I only input positive integers. So do you know any way to make the array bigger? The while should be ok no? Thank you for the answer btw.
2nd Jan 2020, 5:22 PM
javier mateos manzano
javier mateos manzano - avatar
+ 1
You can't make the same array bigger, you can make another one that has more space and then assign it to the pointer you created. In steps it would look like: 1. Create bigger array 2. Copy values from smaller to bigger 3. Free the memory of smaller array 4. Assign bigger array to pointer.
2nd Jan 2020, 5:45 PM
Jakub Stasiak
Jakub Stasiak - avatar