Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an array without specific size?

How can I declare an array without specific size as a class member? I want to set the size of this array immediately in the class constructor. Is it possible to do such thing without using the heap or without resizing the array?

like image 381
Shelef Avatar asked Jun 23 '13 08:06

Shelef


2 Answers

Variable length arrays are not allowed by C++ standard. The options you have are:

  • Use a std::vector or
  • Use a pointer to dynamic memory

Note that Variable length arrays are supported by most compilers as a extension, So if you are not worried of portability and your compiler supports it, You can use it. ofcourse it has its own share of problems but its a option given the constraints you cited.

like image 65
Alok Save Avatar answered Nov 15 '22 00:11

Alok Save


C++ requires the size of an automatic storage array to be known at compile time, otherwise the array must be dynamically allocated. So you would need dynamic allocation at some level, but you don't have to concern yourself with doing it directly: just use an std::vector:

#include <vector>

class Foo
{
 public:
  Foo() : v_(5) {}
 private:
  std::vector<int> v_;
};

Here, v_ is a vector holding ints, and is constructed to have size 5. The vector takes care of dynamic allocation for you.

In C++14, you will have the option of using std::dynarray, which is very much like an std::vector, except that its size is fixed at construction. This has a closer match to the plain dynamically allocated array functionality.

like image 25
juanchopanza Avatar answered Nov 14 '22 22:11

juanchopanza