views:

169

answers:

5

I want to statically allocate the array. Look at the following code, this code is not correct but it will give you an idea what I want to do

class array
{
  const int arraysize;
  int array[arraysize];//i want to statically allocate the array as we can do it by non type parameters of templates
public:
  array();
};

array::array():arraysize(10)
{
  for(int i=0;i<10;i++)
    array[i]=i;
}

main()
{
  array object;
}
A: 

C++ doesn't allow variable-length arrays (i.e. ones whose sizes are not compile-time constants). Allowing one within a struct would make it impossible to calculate sizeof(array), as the size could differ from one instance to another.

Consider using std::vector instead, if the size is known only at runtime. This also avoids storing the array size in a separate variable. Notice that allocating from heap (e.g. by std::vector) also allows bigger arrays, as the available stack space is very limited.

If you want it a compile-time constant, take a template parameter. Then you should be looking for Boost.Array, which already implements it.

Tronic
A: 

The array size must be a compile time constant. You are almost there, you just need to initialize the const and make it a static as well. Or, use a dynamic array or a vector.

dirkgently
+1  A: 

It has to be done using template parameters, otherwise sizeof(array) would be different for every object.

This is how you would do it using template parameters.

template <int N>
class array
{
   int data[N];

   // ...
};

Or, you could use an std::vector if you don't mind dynamic allocation.

Peter Alexander
+1  A: 

If your array size is always the same, make it a static member. Static members that are integral types can be initialized directly in the class definition, like so:

class array
{
  static const int arraysize = 10;
  int array[arraysize];

  public:
    array();
};

This should work the way you want. If arraysize is not always the same for every object of type array, then you cannot do this, and you will need to use template parameters, dynamically allocate the array, or use an STL container class (e.g. std::vector) instead.

Tyler McHenry
A: 

EDIT: note about this answer: This is most likely the wrong way to do this for your situation. But if you really need it to be an array (not a vector or whatever) and you really need it to be dynamically allocated, do the following:

class array
{
  int *p_array;

  public:
    array(int size);
};

array::array(int size)
{
p_array = malloc(size * sizeof(int));
}

Just make sure you clean up (IE free p_array in your descructor)

David Oneill