如何将默认浮点值初始化为结构数组?

时间:2022-03-20 13:31:58

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 .

如何将r和i成员inialize为0?没有循环所有数组?并保持跨平台。

1 个解决方案

#1


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).

其他人建议使用calloc或memset;只有当你知道你只编写一个使用浮点表示的平台时,这些才会起作用,其中所有位零表示0.f,例如IEEE754。 (我假设kiss_fft_scalar是浮动的,正如你的标题所示)。

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.

这会将所有值初始化为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]; .

NB。不要强制转换malloc,即使在编译时没有确切知道大小但是已知它很小,你可以选择通过编写kiss_fft_cpx spectrum [size]来避免malloc / free; 。

#1


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).

其他人建议使用calloc或memset;只有当你知道你只编写一个使用浮点表示的平台时,这些才会起作用,其中所有位零表示0.f,例如IEEE754。 (我假设kiss_fft_scalar是浮动的,正如你的标题所示)。

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.

这会将所有值初始化为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]; .

NB。不要强制转换malloc,即使在编译时没有确切知道大小但是已知它很小,你可以选择通过编写kiss_fft_cpx spectrum [size]来避免malloc / free; 。