3

i have this bits of code :

typedef struct {
    kiss_fft_scalar r;
    kiss_fft_scalar i;
}kiss_fft_cpx;

kiss_fft_cpx* spectrum;
spectrum = (kiss_fft_cpx*)malloc( sizeof(kiss_fft_cpx)* 2024);

how to inialize both r and i members to 0? without looping all the array? and keep it cross platform .

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
user63898
  • 29,839
  • 85
  • 272
  • 514

1 Answers1

3

Portably:

for ( size_t i = 0; i < 2024; ++i )
    spectrum[i].i = spectrum[i].r = 0;

Others have suggested using calloc or memset; those will only work if you know you are only coding for a platform that uses a floating point representation in which all-bits-zero means 0.f, such as IEEE754. (I'm assuming that kiss_fft_scalar is float as your title suggests).

If the size is known at compile-time then you can write:

kiss_fft_cpx spectrum[2024] = { 0 };

which will initialize all the values to 0.

NB. Don't cast malloc and even if size is not known exactly at compile-time but known to be small, you have the option to avoid malloc/free by writing kiss_fft_cpx spectrum[size]; .

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365