Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare an array without knowing its size? C++ [duplicate]

Tags:

c++

arrays

I have to write a program that reads a string of numbers from user input until it reads 0. For example if the values introduced are 1, 2, 3, 0 then the array X will contain 1, 2 and 3 and the array size will be 3. There is no specified limit for the number of values inserted and I can't just declare an array of any size so is there a way to dynamically increase the size of the array to be able to hold more int values as they are being read?

like image 272
Andrei Ardelean Avatar asked Mar 13 '26 06:03

Andrei Ardelean


2 Answers

You can use a std::vector, which is a variable-length collection to which you can add elements. It manages reallocation automatically when needed. For example:

std::vector<int> values;
values.push_back(0);
values.push_back(1);
...
like image 127
jtbandes Avatar answered Mar 15 '26 20:03

jtbandes


It's called Dynamic Memory Allocation check another question here

But normally i'd use a vector

#include <vector>

using namespace std;
int main(){
   vector<int> v;
   int x;
   while(cin>>x && x != 0){
      v.push_back(x);
   }
}

You should note that vector class only exists by implementing dynamic memory allocation. It's just there for you and you don't need to do all the hard work like reserving and destroying the allocated memory...

like image 38
M.M Avatar answered Mar 15 '26 19:03

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!