Undefined Behaviour
Undefined Behaviour

Reputation: 749

variable-sized array type ‘int [size]’ is not a valid template argument

I am getting following error in c++ program :

variable-sized array type ‘int [size]’ is not a valid template argument

for following program:

#include <iostream>
using namespace std;

template <typename T>
void func (T& Array)
{
    cout << "Hi";
}

int main ()
{
    int size = 100;
    int arr [100];
    int arr1 [size];
    func (arr);   // compiled
    func (arr1);  // gives error
}

Please Help me to resolve this. I want to take size of array from some variable. Thanks in advance.

Upvotes: 2

Views: 2673

Answers (2)

Neb
Neb

Reputation: 2280

Replace:

int size = 100;

with

const int size = 100;

In this way, the compiler knows that size will not change and can properly allocate space for the static array arr1

Upvotes: 6

yoloswagster
yoloswagster

Reputation: 1

In C++ you can't define array's size using variable. I suggest you to replace this array with vector or define a preprocessor macro that will hold size for your array.

Upvotes: -2

Related Questions