繁体   English   中英

如何在C中将2个float数组合并为1个结构数组

[英]How to merge 2 float arrays into 1 array of structs in c

我想知道是否有可能将2个float数组合并为1个结构数组。

这是我的示例代码。

typedef struct {
    float left;
    float right;
} t_stereo;

int main(int argc, const char * argv[]) {

    float *leftBuf = (float[4]){1,2,3,4};
    float *rightBuf = (float[4]){5,6,7,8};

    t_stereo *stereo; //how to store *leftBuf and *rightBuf into *stereo?

    return 0;
}

因此,我基本上希望* stereo包含* leftBuf和* rightBuf的数据。

我想知道是否有任何简单的解决方案。

你需要做什么。 简而言之。

function toStereo (left, right)

 - loop for each left, right sample.
    - store left sample in left channel, 
    - store right sample in right channel.
 - end loop

typedef struct {
    float left;
    float right;
} t_stereo;

void toStereo(t_stereo* stereoOut, int n, const float* left, const float* right)
{
    // multiplexes left/right channels to stereo buffer
    // n is number of samples
    // assumes stereoOut is not null and points to buffer 
    // that has room for n samples
    while (n--)
    {
        *stereoOut->left = *left++;
        *stereoOut->right = *right++;
        ++stereoOut;
    }
}

int main(int argc, const char * argv[]) 
{
    float *leftBuf = (float[4]){1,2,3,4};
    float *rightBuf = (float[4]){5,6,7,8};

    t_stereo stereo[4];   //will store 4 stereo samples.

    toStereo(stereo, 4, leftBuf, rightBuf);
    return 0;
}

我想最简单的解决方案是:

t_stereo *stereo = malloc(sizeof(t_stereo) * DATALEN);

int i;
for (i = 0; i < DATALEN; i++)
{
    stereo[i].left = leftBuf[i];
    stereo[i].right = rightBuf[i];
}

DATALEN定义缓冲区的长度

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM