Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable-sized object may not be initialized Error despite initialization

Tags:

c++

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?

like image 659
Alon Avatar asked Jan 27 '23 19:01

Alon


2 Answers

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;
}
like image 83
kanstar Avatar answered Feb 12 '23 16:02

kanstar


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;
like image 44
P.W Avatar answered Feb 12 '23 16:02

P.W