你如何声明循环缓冲区?

时间:2014-07-06 02:36:13

标签: c

/**
 * ring_buffer_set - update the ring buffer with the given value
 * @lq_recv: pointer to the ring buffer
 * @lq_index: index to store the value at
 * @value: value to store in the ring buffer
 */
static void ring_buffer_set(uint8_t lq_recv[], uint8_t *lq_index,
                   uint8_t value)
{
    lq_recv[*lq_index] = value;
    *lq_index = (*lq_index + 1) % 64;
}

/**
 * ring_buffer_set - compute the average of all non-zero values stored
 * in the given ring buffer
 * @lq_recv: pointer to the ring buffer
 *
 * Returns computed average value.
 */
static uint8_t ring_buffer_avg(const uint8_t lq_recv[])
{
    const uint8_t *ptr;
    uint16_t count = 0, i = 0, sum = 0;

    ptr = lq_recv;

    while (i < 64) {
        if (*ptr != 0) {
            count++;
            sum += *ptr;
        }

        i++;
        ptr++;
    }

    if (count == 0)
        return 0;

    return (uint8_t)(sum / count);
}

1)lq_recv[]是循环缓冲区,但它看起来像一个普通数组?

2)*lq_index = (*lq_index + 1) % 64的目的是什么?

2 个答案:

答案 0 :(得分:5)

  1. A&#34;循环缓冲区&#34;是一种以特定方式使用的数组。它没有与任何其他阵列声明任何不同。

  2. 它正在更新从中读取的数组的索引并将其保持在数组的范围内。

答案 1 :(得分:4)

  1. 循环缓冲区当然是一个普通数组,但是一旦它到达最后一个元素,你就会重置数组索引器。
  2. 使用模数运算符(%)可确保数组索引在到达最后一个元素时重置为0.