PDA

View Full Version : Dumb question about complex arrays in c++


Dr Transport
Jul15-04, 09:11 PM
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.

AKG
Jul16-04, 10:25 AM
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.

chroot
Jul16-04, 01:06 PM
Not quite AKG. You forgot the star:

Compex *array = new Complex[n];

- Warren

Dr Transport
Jul18-04, 10:41 AM
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.

dduardo
Jul18-04, 11:51 AM
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.

chroot
Jul18-04, 02:05 PM
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

Dr Transport
Jul18-04, 05:36 PM
I was afraid of that. I'll have to mess around with it......

Thanks

dt

Hurkyl
Jul18-04, 05:57 PM
Could always make a vector of vectors; that's relatively painless.

Dr Transport
Jul18-04, 09:57 PM
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.