gpt4 book ai didi

C99复铸件

转载 作者:太空狗 更新时间:2023-10-29 15:36:29 25 4
gpt4 key购买 nike

我有一些 C99 代码,我需要将一个 2n double 组转换为一个 n double 复数数组。我用

static void real_to_complex(const double *r, size_t n, double complex *z)
{
size_t i;

for (i=0 ; i<n ; i++)
z[i] = r[2*i] + r[2*i + 1]*I;
}

这是代码的性能关键部分,我真的宁愿不必创建一个新的存储区域 z 并承担复制的费用,而是我想将这些函数调用替换为

z = (double complex*)r;

有什么方法可以做到这一点并保持符合标准吗?我知道双复数保证与两个 double 组具有相同的布局——也许我可以通过编译器检查这个布局是(实数,虚数)还是(虚数,实数)?

最佳答案

complex 数组的第一个元素对应于实部,第二个元素对应于虚部。

引自 the publicly available draft of C11 Standard

6.2.5/13 Each complex type has the same representation and alignment requirements as an array type containing exactly two elements of the corresponding real type; the first element is equal to the real part, and the second element to the imaginary part, of the complex number.

示例程序

#include <complex.h>
#include <stdio.h>

int main(void) {
double x[] = {42, 2, 41, 1, 0, 0};
_Complex double *y = (void*)x;
while (creal(*y) > 0) {
printf("%f + %fi\n", creal(*y), cimag(*y));
y++;
}
return 0;
}

关于C99复铸件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11827280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com