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
2
  • 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. Commented Feb 28, 2020 at 4:02
  • You may want to check your C++ book. There's an int missing before main. Commented Feb 28, 2020 at 7:58

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@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++ and is a vendor-specific extension that only a few compilers support.

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.