0

Is it possible to initialise a char array inside a template function with size contained in a static * int?

.header

static int * array_size;

template <class T>
void f(T value)
{
    char buffer[*array_size];
}

Or is there a way to initialize "array_size" so that the template has a default value to use?

3
  • Why do you want to use a pointer here? The expression inside the [] must be a constant expression, therefore you cannot use modifiable types. static constexpr int const* array_size = &my_size; (where my_size is e.g. a constexpr int) is possible, but not sure why you want to use that. Commented Apr 10, 2014 at 12:05
  • i am trying to have a buffer that i can change its size Commented Apr 10, 2014 at 12:09
  • Array sizes must be known at compile time. You could use a std::vector instead of the array. Commented Apr 10, 2014 at 12:10

2 Answers 2

3

static int * array_size won't work because the data inside the pointer is modifiable and thus cannot be determined at compile-time.

If you are using C++11 I would suggest

constexpr int array_size = 42;

If you cannot use C++11 I would use:

static const int array_size = 42;

In both cases you create your buffer like this:

char buffer[array_size];

So without the asterisk.

If you cannot find out the size of the buffer at compile time (so the size is dependant on runtime-decisions) you need to use a dynamic array, preferably encapsulated into a std::vector:

std::vector<char> bufferVec(myDynamicSize); // Use any integer you want to
char *buffer = &bufferVec[0]; // Use this buffer as a standard array 
                              // with size myDynamicSize OR use the std::vector
                              // directly (much cleaner)
Sign up to request clarification or add additional context in comments.

Comments

0

Qualifyer for array_size must be constant, otherwhise you will end with expected constant expression. Static keyword is irrelevant.

const int array_size = 42;
char buffer[array_size];

Pointer dereferencing will not work even if the pointer points to a const

const int a = 42;
int const * const array_size = &a;
char buffer[array_size]; // error C2057: expected constant expression

You also might paste in the array_size via a template parameter:

template <class T, int array_size>
void f(T value)
{
  char buffer[array_size];
}

f<int, 42>(100);

1 Comment

"Pointer dereferencing will not work even if the pointer points to a const" It will work if the pointer has been declared constexpr (in this case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.