This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: coding question


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";
> 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]