gpt4 book ai didi

C 基本环形缓冲区问题

转载 作者:行者123 更新时间:2023-11-30 18:51:51 26 4
gpt4 key购买 nike

我在尝试制作的基本环形缓冲区上遇到了问题。我似乎无法让它正确环绕。当我达到元素数量 = buffer_length 时,行为变得不可预测,并且在调试器中它只会显示第一个 * 元素。

任何人都可以看到我遗漏的明显错误。

提前致谢。

#include "stdafx.h"
#include <stdio.h>
#include <string.h>

#define BUFFER_LENGTH 8

typedef struct circular_buffer
{
float buffer[BUFFER_LENGTH];
float *buffer_end;
float *head;
float *tail;
size_t count;
} circular_buffer;

circular_buffer buffer;

void cb_init(circular_buffer *cb)
{
memset(cb->buffer, 0, BUFFER_LENGTH * sizeof(float));

cb->buffer_end = (float *)cb->buffer + BUFFER_LENGTH * sizeof(float);
cb->count = 0;
cb->head = cb->buffer;
cb->tail = cb->buffer;
}

void cb_push_back(circular_buffer *cb, float item)
{
*cb->head = item;
cb->head = (float *)cb->head++;
if (cb->head == cb->buffer_end)
cb->head = &cb->buffer[0];
cb->count++;
}

float cb_pop_front(circular_buffer *cb)
{
float item = 0;
item = *cb->tail;
cb->tail = (float*)cb->tail++;
if (cb->tail == cb->buffer_end)
cb->tail = &cb->buffer[0];
cb->count--;
return item;
}

float cb_peek_front(circular_buffer *cb, size_t pos)
{
float *arrPos;
size_t i = 0;
do
{
arrPos = (float*)cb->tail + i;
if (arrPos == cb->buffer_end)
arrPos = cb->buffer;
i++;
} while (i <= pos);

return *arrPos;

}

int _tmain(int argc, _TCHAR* argv[])
{
cb_init(&buffer);

cb_push_back(&buffer, 5);
printf("%f\n",cb_pop_front(&buffer));
cb_push_back(&buffer, 6);
printf("%f\n", cb_pop_front(&buffer));
cb_push_back(&buffer, 7);
printf("%f\n", cb_pop_front(&buffer));
cb_push_back(&buffer, 8);
printf("%f\n", cb_pop_front(&buffer));
cb_push_back(&buffer, 9);
printf("%f\n", cb_pop_front(&buffer));
cb_push_back(&buffer, 10);
printf("%f\n", cb_pop_front(&buffer));
cb_push_back(&buffer, 11);
printf("%f\n", cb_pop_front(&buffer));
cb_push_back(&buffer, 12);
printf("%f\n", cb_pop_front(&buffer));

// stops working here
cb_push_back(&buffer, 13);
printf("%f\n", cb_pop_front(&buffer));

cb_push_back(&buffer, 14);
printf("%f\n", cb_pop_front(&buffer));


return 0;
}

最佳答案

这个

cb->buffer_end = (float *)cb->buffer + BUFFER_LENGTH * sizeof(float);

不会做你期望的事情。

修改为

cb->buffer_end = cb->buffer + BUFFER_LENGTH;

让它指向缓冲区的最后一个元素。

<小时/>

另外,删除所有那些无用的转换为 (float *)

<小时/>

而且你想替换

cb->head = (float *)cb->head++;

通过一个简单的

cb->head++;

cb->tail = (float*)cb->tail++;

cb->tail++;

关于C 基本环形缓冲区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35869507/

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