+ 3

Arrays in c++?

Just a random question about arrays in c++ So every array must have it's size declared right? What do we do if we don't know what the size will be? I came from JS so I'm used to arrays just kinda being there and not needing it's size declared.

15th Oct 2018, 10:05 PM
Daniel Cooper
Daniel Cooper - avatar
7 Respostas
+ 4
If the array will still have a fixed size, but you want to get the size from the user, for example, you can allocate it dynamically: int arr* = new int[10] This creates an array of ten elements, but it can be any size, essentially. However, this only applies if you still know some kind of size. If you need the array to shrink and grow, then you will want to use vectors. They are 'better' arrays and support most of the operations you might know from JS. Also, they don't neccessarily need to be constructed with a size. I'd highly suggest you to make yourself familiar with them if you want to advance in C++: http://www.cplusplus.com/reference/vector/vector/ https://en.cppreference.com/w/cpp/container/vector
15th Oct 2018, 10:24 PM
Shadow
Shadow - avatar
+ 2
Thanks Shadow I'll look into vectors.
15th Oct 2018, 10:35 PM
Daniel Cooper
Daniel Cooper - avatar
+ 2
I wish Somebody could give Daniel Cooper another QnA solution.. https://www.sololearn.com/post/38046/?ref=app
16th Oct 2018, 6:17 AM
Calviղ
Calviղ - avatar
+ 2
neptune rose that would cause a compiler error. It is illegal in C++ to declare an array of size 0.
17th Oct 2018, 8:58 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 1
Акбар Юсупов Calviղ is most definitely a good person y u insult?
16th Oct 2018, 1:18 PM
Daniel Cooper
Daniel Cooper - avatar
0
Unacceptable comment
17th Oct 2018, 6:48 AM
Beyar
Beyar  - avatar
0
int arr[] = {};
17th Oct 2018, 7:58 AM
neptune rose