Santosh Sahu
Santosh Sahu

Reputation: 2244

static array definition error c++

Error while declaring static array inside a function with function parameter

 int fun(int x)
 {
      int a[x];  //No Error
      static int b[x];   //Error "storage size of x is not constant
      int *f = new int[x+1];  //NO ERROR--NEW OPERATOR USED TO DEFINE THE ARRAY
 }

What should be changed in 2nd line inorder to declare the array "b" without any error.

Upvotes: 0

Views: 367

Answers (2)

Jobs
Jobs

Reputation: 3377

There's no way to declare a 'const' array with non-constant storage size.

Instead use a vector.

int fun(int x)
{ 
  const int b[x];   //Error "storage size of x is not constant
  vector<int> b(x); //ok
}

Also int a[x] isn't correct either. C99 does support non constant array size, but generally, x needs to be a constant.

Upvotes: 1

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36391

Your problem is that you cannot define a array of const something without initializing it and if it is of a dynamic size there is no way to initialize it!

Upvotes: 1

Related Questions