Defining and initializing complex arrays in C++

  • Context: C/C++ 
  • Thread starter Thread starter Dr Transport
  • Start date Start date
  • Tags Tags
    Arrays C++ Complex
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
8 replies · 7K views
Messages
2,603
Reaction score
785
In trying to learn C++ (I'm an old FORTRAN guy), I am unable to figure out how to define and initialize a complex array. Single complex numbers are straight forward, but going further has me perplexed some.

Thanks in advance.
 
Physics news on Phys.org
I assume you have a Complex class.

Complex *array = new Complex [n];

I think that should work. "new" is a keyword, "array" is the variable name for the array, and "n" would be an integer variable, of course you can put in your own number if you want, e.g. replace "n" with "5".

EDITED based on chroot's comment.
 
Last edited:
Not quite AKG. You forgot the star:

Compex *array = new Complex[n];

- Warren
 
Thanks, how about a 2d array?

complex **array = new complex [n][n]; ?

and maybe an n-d array, I use tensors in 3-d and 4-d in my old fortran codes.
 
Using dynamic memory allocation for multi dimensional arrays isn't as trivial as you think. You actually have to create an array of arrays. You'll first need to allocate a single dimensional array. Then using a loop allocate an array within each cell. You can get some pretty nasty code especially with higher dimesions. Believe it or not, this is one thing you probable want to stick with fortran to do.
 
You only need to do as dduardo suggested if you are using non-trivial data types. If you're just making a multi-dimensional array of ints or doubles, etc., you don't need to do anything special besides allocating the memory with the new operator.

- Warren
 
Could always make a vector of vectors; that's relatively painless.
 
I think I got it figured out, as Hurkyl and dduardo, either make a vector of vectors or an array of arrays. After I got a couple of hints from the community, it actually came very quickly.

On to other things about C++...maybe I'll succeed in converthing those old codes I have to further some old projects that I can't seem get working on other machines and operating systems.