0

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.

4
  • What do you think of the compiler suggestion ? In c++ you should use std::vector<> in such cases Commented Jan 1, 2015 at 14:49
  • 1
    The root problem here is that const int b[x] is allocating memory at compile time so x cannot be a variable (it's value is not known at compile time), whereas int *f = new int[x+1] allocates memory at run time (because of the new), so x can be a variable. As @quantdev says, use a different type, or use dynamic memory allocation, such as int *b = new int[x];. Commented Jan 1, 2015 at 14:54
  • 1
    It's also useless if it were to work. You'd be creating a const array at runtime and be unable to initialise it with usefull data. Commented Jan 1, 2015 at 14:58
  • 3
    Note that int a[x]; is not valid C++ either. It's a C feature that certain compilers, most notably GCC, accept in C++ as a language extension. Do use std::vector instead. Commented Jan 1, 2015 at 15:09

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

vector<int> is not a replacement for const int [] because he wants to store const ints.
@Jean-BaptisteYunès: Then do vector<const int> and provide initialization data.
@BenVoigt : Feel free to make those changes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.