0
int shifts[c] = {0};

The c is defined. Error: shifts maybe not be initialized. Why? What am I doing wrong here? I think it has something to do with c, but I am not sure. If I can't use the current declaration, how do I get around it? I tried it with vectors first:

vector<bool> shifts(c, false)

But, it didn't work. Had bad_alloc error.


int max = 0, min = 10000;
for (int i = 0; i != 2*no_shifts; ++i) {
    int x;
    fin >> x;
    time.push_back(x);

    if (max < x)
        max = x;

    if (min > x)
        min = x;
}
c = max - min + 1;
10
  • c has to be a compile-time constant for the array declaration. Is it? Commented May 29, 2014 at 21:24
  • What's the value of c when you execute that line? Commented May 29, 2014 at 21:26
  • Yes. Umm, I don't know. 'c = max - min + 1' max and min are int. Is there something wrong with this? Commented May 29, 2014 at 21:26
  • @IshaanSingh How are max and min defined? Can you show more code, at least enough to see exactly what c gets set to, ideally an entire but short program Commented May 29, 2014 at 21:28
  • 1
    c is not a constant expression since it involves max and min which are non-const. Variable-length arrays are not part of C++ and your compiler may have restrictions on how they can be used. (In C99, variable-length arrays may not be initialized.) Commented May 29, 2014 at 21:36

1 Answer 1

3

Based solely on c = max - min + 1; it seems that you are trying statically initialize an array without a compile time constant. Either use a dynamically allocated array or std::vector if you need something that can have it's size determined at runtime.

Edit: You may actually want to consider using std::bitset instead as an alternative container.

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

3 Comments

So, if I use vector<bool> shifts(c, false), will it work? How do you get the grey padding around the code (inline)?
std::vector<bool> shifts(c, false); should make a vector with c amount of bool all set to false with the default allocator. You use the ` key to inline code snippets.
Make sure you create the vector after calculating the value of c to use

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.