This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: coding question
- From: Michael Clark <michaeljclark at mac dot com>
- To: "Moreno, Cesar A" <cesar dot a dot moreno at lmco dot com>
- Cc: "gcc at gcc dot gnu dot org" <gcc at gcc dot gnu dot org>
- Date: Wed, 12 Dec 2018 11:39:51 +1300
- Subject: Re: coding question
- References: <0895aa5246d1430ca8a87a2b56ba9343@lmco.com>
Hi Cesar,
> On 12/12/2018, at 10:31 AM, Moreno, Cesar A <cesar.a.moreno@lmco.com> wrote:
>
>
>
> HOW do I malloc or new an array of complex numbers in GNU C++ code ?
> MALLOC does not work, how do I use MALLOC correctly or NEW ?
>
> I made a struct called complex (for a complex number with realp and imagp)
> And I want to make an array of 128 locations (where each location includes a realp and imagp)
use vector<complex> and the “indexed for comprehension”. and don’t hard code a constant for the cardinality of a set. the compiler knows how to do this safely e.g.:
struct ℂ { float r; float i; };
vector<ℂ> v = { { 1, 0 }, { 0, 1 } };
for (/* auto */ [ i, c ] : v) {
printf(“%zu: (%f, %f)\n” i, c.r, c.i);
};
I haven’t compiled this so it might have some coding bugs. I might have missed auto or it doesn’t work or something. uncomment auto if it doesn’t compile. also your local type aliases may differ from mine.
Michael
> Struct complex
> {
> Float realp;
> Float imagp;
> }
>
> // tdin is a pointer to an array of complex numbers
> complex* tdin;
>
>
> // form the array with MALLOC or whatever works in GNU C++
> tdin = (complex*) malloc ( 128 * sizeof (complex) );
>
>
> then I can print the contents of the array with
>
> for (int k; k<128; k++)
> { cout << tdin[k].realp << " and " << tdin[k].imagp << "endl";
>