如何在c中将2个浮点数组合成1个结构数组

时间:2017-06-27 05:18:50

标签: c arrays pointers struct

我想知道是否可以将2个浮点数组合成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的数据。

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

我认为最简单的解决方案是:

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定义缓冲区的长度