0

C++ array initialize?

How do you initialize an array without knowing the length? Like in a class for example: class arr { private: // initialize array here without length public: arr(int length){ // set array length here } } I’m new to c++ and I don’t really know how you would do this, also I don’t want to use a vector.

18th Jul 2022, 7:28 PM
ITDW
5 Answers
+ 2
class arr { private: int *n; // declare int* pointer public: arr(int length){ n = new int[length]; // dynamically allocate memory by constructor. } }
18th Jul 2022, 8:04 PM
Jayakrishna 🇼🇳
+ 3
Why don't you want to use a vector?
19th Jul 2022, 8:13 AM
XXX
XXX - avatar
+ 1
Also, you should free the array inside the destructor.
19th Jul 2022, 2:46 AM
Lama
Lama - avatar
+ 1
ITDW I don't think so. Vectors are more inefficient than arrays stored on the stack since they have to allocate memory on the heap, but you can't achieve what you want using static arrays anyways. You need to allocate on the heap, and you might as well let the vector class handle that for you. Since you know the length beforehand, you can do something like this class arr { private: std::vector<int> v; public: arr(int length) { v.reserve(length) } }; This does the same thing that @Jayakrishna's code does, with the added advantage of the memory being allocated and freed automatically for you. Remember, you should avoid manual memory management as much as possible in C++.
19th Jul 2022, 7:02 PM
XXX
XXX - avatar
0
I heard vectors are inefficient and i would rather use an array
19th Jul 2022, 6:13 PM
ITDW