C中循环缓冲区中的反向遍历

use*_*997 3 c linux

我有以下数组,我打算将其用作循环缓冲区。

int array1[20]; 
Run Code Online (Sandbox Code Playgroud)

该数组由一个线程写入并由另一个线程读取。在阅读时,我需要读取写入该数组的最后 3 个值。

写作工作正常。我用

writeIndex = (writeIndex + 1) %20;
Run Code Online (Sandbox Code Playgroud)

来写。这很好地将数组索引 0 滚动到 19。

为了阅读,我正在使用

readIndex = (readIndex -1)%20;
Run Code Online (Sandbox Code Playgroud)

但它不起作用当我尝试从索引 0 到 19 时。

Tod*_* Li 6

你的代码

readIndex = (readIndex - 1) % 20;
Run Code Online (Sandbox Code Playgroud)

不工作,因为当readIndex以 0 开头时,(readIndex - 1) % 20将评估为 -1,然后您的数组访问将超出范围。

在这种情况下,您不想处理负数。为了避免这种情况发生,您可以简单地将 20 添加到值中:

readIndex = (readIndex - 1 + 20) % 20;
Run Code Online (Sandbox Code Playgroud)

或者干脆

readIndex = (readIndex + 19) % 20;
Run Code Online (Sandbox Code Playgroud)

所以当readIndex从 0 开始时,你可以向后回绕到 19。