Aegon The Unworthy Aegon The Unworthy - 7 months ago 51
C++ Question

Creating an array of Complex numbers in C++

I want to create an array to store complex numbers such that First input is number of entries n . Each entry is first real part of number followed by complex part .

Eg: n=2
1.0 -1.0
0 3

is representation of numbers 1-i , 3i respectively .
This is what I tried .


typedef std::complex<double> Complex;

int main() {
int n;
Complex A[n];

for(int i=0;i<n;i++)

for(int i=0;i<n;i++)
std::cout<<A[i]<<" ";

return 0 ;

I am new to the c++ programming . Please tell me where I went wrong .

Answer Source

First, variable length arrays as you introduce with cin >> n; Complex A[n] are not part of the C++ standard and might not be supported by your compiler. Second, if your compiler supports VLAs in general, it will not support to create a VLA of a non-POD (plain old data) type like std::Complex.

To overcome both issues, use a std::vector instead of the plain array:

std::vector<Complex> A(n);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download