0

I know this sound easy to you guys but I think this may be different

Here is my simple code in which i am getting error in declaring Array

#include<iostream>
using namespace std;

int top=-1,capacity=2;
int arr[capacity];

main(){
}//main
David G
  • 94,763
  • 41
  • 167
  • 253
shahmir
  • 15
  • 5
  • Sorry, C++ does not work this way. Array dimensions must be constants. Just because it's a variable that's been initialized with some value doesn't make the array dimension a constant. – Sam Varshavchik Feb 28 '20 at 04:02
  • You may want to check your C++ book. There's an `int` missing before `main`. – MSalters Feb 28 '20 at 07:58

1 Answers1

1

A fixed length array needs a compile-time constant to declare its size. You need to declare capacity as const or constexpr in order to use it in an array declaration, eg:

#include <iostream>
using namespace std;

int top = -1;
const int capacity = 2;
int arr[capacity];

main(){
}

If you want to define the capacity at runtime then you need to use a dynamic array, like std::vector, eg:

#include <iostream>
#include <vector>
using namespace std;

int top = -1, capacity;
vector<int> arr;

main(){
    capacity = ...;
    arr.resize(capacity);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • @shahmir "*sometime its work fine*" - if the variable is not a compile-time constant then it CAN'T be used to declare a fixed length array statically, period. You might be thinking of a "variable length array", which is [not legal C++](https://stackoverflow.com/questions/1887097/) and is a vendor-specific extension that only a few compilers support. – Remy Lebeau Feb 28 '20 at 10:33