gpt4 book ai didi

c - 简单循环缓冲区: Need to extend function to overwrite old data

转载 作者:行者123 更新时间:2023-11-30 16:11:29 24 4
gpt4 key购买 nike

我正在尝试实现一个简单的循环缓冲区并覆盖旧数据(只是尝试缓冲区)。实际上我实现了一个缓冲区,但它并没有覆盖旧数据。当缓冲区已满时,它不会向数组添加新数据。

我有以下内容:

//Struct with 8 bytes
typedef struct
{
int8 data_A;
int16 data_B;
int8 data_C;
int32 data_D;
} MyData_Struct_t

//The Circular buffer struct
typedef struct {
MyData_Struct_t myData[10]; // 10 elemtns of MyData_Struct_t
int8 write_idx
int8 read_idx
int8 NrOfMessagesinTheQue
} RingBuffer


static MyData_Struct_t myDataVariable = {0}; // Instance of MyData_Struct_t
static RingBuffer myRingBuffer= { 0 }; // Instance of myRingBuffer

myDataVariable.data_A = getData(A); // Lets' say getData() function is called cyclic and new data is received
myDataVariable.data_B = getData(B);
myDataVariable.data_C = getData(C);
myDataVariable.data_D = getData(D);

// Here I call a function to fill the array with data
writeDataToRingbuffer(&myRingBuffer, &myDataVariable);

void writeDataToRingbuffer(RingBuffer *pBuf, MyData_Struct_t *Data)
{
if (10 <= pBuf->NrOfMessagesinTheQue)
{
// Buffer is Full
}

else if (pBuf->write_idx < 10)
{
(void)memcpy(&pBuf->myData[pBuf->write_idx], Data,
sizeof(MyData_Struct_t)); //myData will be read later by another function

if ((10 - 1u) == pBuf->write_idx)
{
pBuf->write_idx = 0u;
}

else
{
pBuf->write_idx += 1;
}

pBuf->NrOfMessagesinTheQue++;
}

else
{
// Out of boundary
}
}

我需要一些想法如何扩展此功能以覆盖旧数据?

非常感谢!

最佳答案

如果您只想覆盖最旧的数据,只需使用索引对缓冲区大小取模即可:

#define BUFFER_SIZE 10  // size of myData

void writeDataToRingbuffer(RingBuffer *pBuf, MyData_Struct_t *Data)
{
(void)memcpy(&pBuf->myData[pBuf->write_idx % BUFFER_SIZE], Data,
sizeof(MyData_Struct_t)); //myData will be read later by another function

pBuf->write_idx += 1;
pBuf->NrOfMessagesinTheQue++;
}

使用此方法,您还可以组合 write_idx 和 NrOfMessageinTheQue,因为您现在不必将索引重置为 0。

关于c - 简单循环缓冲区: Need to extend function to overwrite old data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596921/

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