Initializing an Array of Variable Sizes Inside a Class

I am trying to initialize an array of size n based on the input argument of my constructor. It works:

//Inside Header class runningAverage{ private: byte n; float array[10]; public: runningAverage(byte); }; //Inside .cpp runningAverage::runningAverage(byte a){ n = a; for (byte i = 0; i<n; i++) { array[i] = 0; } } 

and this does not work:

 //Inside Header class runningAverage{ private: byte n; float array[]; public: runningAverage(byte); }; //Inside .cpp runningAverage::runningAverage(byte a){ n = a; for (byte i = 0; i<n; i++) { array[i] = 0; } } 

I want to initialize an array so that it is the size specified by n. This way, I do not lose memory by arbitrarily defining an array of float [256] or something like that. Any help is appreciated!

+2
source share
3 answers

You must actually allocate an array; and you want to use a pointer type, float array[] not what you think there. Since juanchopanza reminds us, you also want to either turn off the copy constructor, or the assignment operator, or implement those that make the proper deep copy.

 //Inside Header class runningAverage{ private: byte n; float *array; // <= correct type public: runningAverage(byte); ~runningAverage(); // <= you'll need a destructor to cleanup private: runningAverage(const runningAverage &); runningAverage & operator = (const runningAverage &); }; //Inside .cpp runningAverage::runningAverage(byte a){ array = new float[n]; // <= allocate array n = a; for (byte i = 0; i<n; i++) { array[i] = 0; } } // clean up runningAverage::~runningAverage(){ delete[] array; } 

However, if you have some kind of dynamic automatic container (for example, std::vector ), you can use it instead - then you do not need to deal with copy / assignment / destructor / memory management.

+6
source

If you only know the size at runtime, Jason C's answer is what you want. (With comment by juanchopanzas)

If the size is known at compile time, you can use templates:

 template < int SIZE > class runningAverage { float array [ SIZE ]; }; runningAverage < 10 > ra; 

Or use classes like std::array instead of std::vector .

+3
source
  • Your member must be a pointer so that dynamic memory allocation can occur when building an object: float *array; .
  • In the constructor, use array = new float[a];
  • In the constructor, initialize using memset rather than a loop.
  • You have a destructor to free memory with this line: delete[] array;
  • To get it for compilation, you need the following line: #include <new>
  • To link, remember to enable the linker flag -lstdc++ when using g++ .

Since you seem to be a beginner, take a look at this useful link for learning: http://www.cplusplus.com/doc/tutorial/dynamic/

0
source

Source: https://habr.com/ru/post/1204033/


All Articles