Hello,

I have to use an array, but its length is unknown at the beginning of the program. Is it possible to create such array and after that give it the desired length?

Thank you!

create a pointer to the array then use "object pointed to"=new "type"

ex:


double* array;

array=new double[69];

Or if you really want to get crazy, you can have the user input the size, but make sure to remember data is stored in the 0th spot of an array (array[0]):

double* array;
int size;

cout<<"Enter size of the array : ";
cin>>size;
array=new double[size];

Edited 6 Years Ago by gnarlyskim: n/a

Comments
Great idea

Hello,

I have to use an array, but its length is unknown at the beginning of the program. Is it possible to create such array and after that give it the desired length?

Thank you!

If the length is varying, I'd recommend using vectors instead as they can change size to accommodate the number of items stored in them and don't need to be declared with a size.

However, if you'd like to use an array, and all of the items will be added at once later in the program, you could maybe declare it at that time?

Example of an array declared and initialized at the same time without stating its size:

int myArray[] = {1,2,3,4,5,6,7,8,9,10};

The above array's size is automatically determined by how many things are to be added to it during its initialization/declaration

Otherwise, if you'd like to use a vector for the ability to have changing sizes:

vector<int> myVect;

Then, later you'd state myVect.push_back(1); for example, to add 1 to the end of the vector

For vectors, you'd need to #include <vector> also

Really up to you and how you'd like your program to run. If you need to use an array, and can't initialize it when declaring it, then you'd have to just make sure you declare it with a size larger than it'll need later to prevent an out of bounds exception during the program's execution

create a pointer to the array then use "object pointed to"=new "type"

ex:


double* array;

array=new double[69];

Wow, very good idea. I haven't used this technique before but its a great idea for sure. +1 to you

^^ check edited post for even more fun! haha

Not a bad idea at all. User-supplied array size...creative idea :)

You forgot to include [sarcasm] and [/sarcasm] tags :)

haha although it definitely adds a lot more room for user error, it's an interesting idea

I imagine that technique could be used to allow the program to somewhat auto-determine a good size for the array, depending on program design

I somewhat prefer vectors, myself, as you set and forget them, but if you need to use an array with an unknown size, it's a decent trick

This question has already been answered. Start a new discussion instead.