new array must has a constant size?

When I use "new" to create a array like:

int *a = new a[5];

do I have to declare the array with the constant size? Can I declare like

int *a = new a[];

Thanks in advance.
1
2
3
4
5
6
7
int numbers;
cout << "how many numbers? \n";
cin >> numbers;
int a = new int [numbers];
//...code
delete [] a;
> do I have to declare the array with the constant size?

No. This is fine:
1
2
3
std::size_t n ;
std::cin >> n ;
int* a = new int[n] ;



> Can I declare like int *a = new a[];

I presume you meant: int* a = new int[];
No. The size must be specified (it may be zero).


Use std::vector<>. http://www.mochima.com/tutorials/vectors.html
Thanks for replys. So genenrally, it means the array size can be assigned in runtime, but the size is still a constant, correct?

Thanks.
The size of an array can't change if that's what you mean.
If you need an array that can change size, look into vectors: http://www.cplusplus.com/reference/vector/vector/
Thanks for replys. So genenrally, it means the array size can be assigned in runtime, but the size is still a constant, correct?


If I understand your question, yes and no. You can resize the array's memory block after initial allocation using the C function malloc, but that can get pretty messy unless fully understand what data you may possibly be losing/gaining throughout the life of the pogram.

The previous suggestion to use vectors is probably your best option if you need your array to change its size dynamically throughout the life of the program. If you know its size during compilation, you can hard-code the array's size using *int a[5];*. If you only need to initially allocate memory once in the life of the program and never change its size again, you can use the new operator. If you know the array's size will change throughout the life of the program, definitely use vectors.
Thanks for all replies. Yes, vector is choice if I need the array size change during program running.

I just have another question, is there any advantages of using new to create array compare to "int a[SIZE]"? The only thing it seems that if I use "new", the array size can be very big if you need store a lot of data. I think this may because the array created by new is stored in heap instead of program stack.

Thanks.
Topic archived. No new replies allowed.