4
int main(){
    int sample_rate = 50;

    int t_max = 60*5 ;

    int dimensions = 3;
    int num_samples = sample_rate * t_max;

    double data[dimensions][num_samples] = { { } }; //Error here
    return 0;
}

I understand that the size of an array on the heap must be known during compile time which it is here (3 x 15000). Why am I still getting the error?

7
  • You should copy-paste the exact compilation instruction you do and the exact error you get, because it could be different for other people with different compilers or who use different compiler options. Commented Jan 30, 2019 at 22:45
  • 3
    Mark those four int variables as const int. Commented Jan 30, 2019 at 22:46
  • @PeteBecker solved it, thanks Commented Jan 30, 2019 at 22:52
  • I understand that the size of an array on the heap must be known during compile time This array is on the stack. Commented Jan 30, 2019 at 22:53
  • 1
    If you are using c++11, you should opt for constexpr Commented Jan 31, 2019 at 4:49

2 Answers 2

5

Just use std::vector instead.

#include <vector>

int main(){
    int sample_rate = 50;

    int t_max = 60*5 ;

    int dimensions = 3;
    int num_samples = sample_rate * t_max;

    std::vector<std::vector<double>> data(dimensions, std::vector<double>(num_samples));
    // access data like this
    data[0][0];
    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Although this answer is extremely helpful and I will do what you suggested, it is not the answer to my question so I can't accept it, but take my upvote.
3

The bound (size) of an array when it is specified has to be a constant-expression as per [dcl.array]/1.
The bounds you have specified are not constant expressions. To convert them into such, you either have to prepend const or constexpr (C++11 onward) before the declaration of those four integers like this:

const int sample_rate = 50;

Or

constexpr int sample_rate = 50;

Comments

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.