What if I don't know the size the array is going to have?

Hi guys!

I have a quick question. What if I don't know the size the array I made is going to be and don't want to use vectors or write anything new, is it possible? Does C++ have a built in functionality that allows me to do this?

For example, I have a very large number whose prime factors I am trying to find, and I don't know how many there are. Will pointers work? For example:

int* pointer = new int;
*pointer = first prime factor;

int a = some function that returns the next, in this case second, prime factor ();

pointer[1 (or n, if it is not the second factor)] = a;

If not, my options are to use vectors, write something similar to what vectors do or guess a maximum number for my array, right?

Thanks a lot!
Does C++ have a built in functionality that allows me to do this?

Yes, it's called vector

don't want to use vectors

Why??
No reason at all, this was purely for the sake of curiosity. I just needed to know if it could be done some other way. So, that's a no?

What is the problem with the code I showed? Is it because as I increment the pointer it would eventually point to some address that was already in use?
By "don't know the array size" do you mean, don't know the array size at compile time? Or will never know the exact array size.

You can dynamically allocate array space, but you must know the size (at some point).
1
2
int *array = new array[size];
delete [] array;


If you will never know the exact size of the array, use vectors (because vectors are the C++ built in function for arrays of unknown size).
Last edited on
Well, besides vectors, C++ has other containers, and various libraries have even more of them.

Technical answer is that if you increment a pointer that was obtained from new int; just once, it will not be dereferencable, and if you increment it twice, it will be invalid. In practice, you will very soon reach some address that your process does not own and receive a segfault.
I meant at any time, Thumper!

Got it, thank you both very much!
Topic archived. No new replies allowed.