Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error "array bound is not an integer constant before ']' token"

Tags:

c++

arrays

I am trying to implement a stack using an array but I receive an error.

class Stack{
private:
    int cap;
    int elements[this->cap]; // <--- Errors here
    int top;
public:
  Stack(){
     this->cap=5;
     this->top=-1;
};

The indicated line has these errors:

Multiple markers at this line
- invalid use of 'this' at top level
- array bound is not an integer constant before ']' token

What am I doing wrong?

like image 693
user1849859 Avatar asked May 08 '13 20:05

user1849859


2 Answers

In C++, the size of an array must be a constant known at compile-time. You'll get an error if that isn't the case.

Here, you have

int elements[this->cap];

Notice that this->cap isn't a constant known at compile-time, since it depends on how big cap is.

If you want to have a variably-sized array whose size is determined later on, consider using std::vector, which can be resized at runtime.

Hope this helps!

like image 94
templatetypedef Avatar answered Oct 23 '22 20:10

templatetypedef


You cannot use this in the declaration like that. this is a constant pointer passed to non-static methods in your class. It does not exist outside of that scope.

Such array declarations need constant values/expressions for the size. You don't want that, you want a dynamicly sized container. The solution is to use a std::vector.

like image 45
user123 Avatar answered Oct 23 '22 19:10

user123