Amin
Amin

Reputation: 261

Complex array initialization in c++

There is a problem when I want to define a complex array:

#include<complex.h>

int main(){

int matrix=1000;
std::complex<double> y[matrix];

}

The error is "Variable length array of non-POD element type 'std::complex' Is there something wrong with the definition of array here?

Upvotes: 1

Views: 5043

Answers (5)

brokenfoot
brokenfoot

Reputation: 11629

C++ doesn't allow variable length arrays, either do it dynamically or use a vector.

Upvotes: 1

Marius Bancila
Marius Bancila

Reputation: 16318

The size of arrays must be know at compile time. It must be a constant expression. The value of matrix is only known at runtime. You must make matrix a constant to work.

const int matrix=1000;

The other way around is to use a vector whose size is variable and is initialized at runtime.

int matrix=1000;
std::vector<std::complex<double>> y(matrix);

Upvotes: 1

Baum mit Augen
Baum mit Augen

Reputation: 50053

This kind of array only works with a length that is a constant expression, i.e. the length must be known at compile time.

To get a array of variable length, use an std::vector<std::complex<double>> y (matrix);

You should use std::vector (or std::array in some cases) over C-style arrays anyway.

Upvotes: 2

rw.liang1
rw.liang1

Reputation: 418

You can't statically allocate a C++ array with size being a regular variable, since the value of matrix is not known until the program is executed. Try dynamically allocating your array:

std::complex<double> y = new std::complex<double>[matrix]

When you are doing using it, call:

delete[] y

Upvotes: 1

Christian Aichinger
Christian Aichinger

Reputation: 7227

Your compiler thinks that you are declaring a variable-length array, since matrix is non-const. Just make it constant and things should work:

const int matrix = 1000;
std::complex<double> y[matrix];

The error stems from the fact that variable-length arrays are only allowed for "dumb" data types, e.g. int/char/void* and structs, but not classes like std::complex.

Upvotes: 0

Related Questions