简体   繁体   English

循环缓冲区会重置内存吗?

[英]circular buffer resets memory?

When this cycles back around dd[0] is set to 0 as apposed to 256.1 ?? 当此循环返回时,dd [0]设置为0,如256.1 ??。 It seems like 'dd' memory is resetting with 'aa' back to 0. 似乎'dd'内存正在将'aa'重置为0。

unsigned char aa = 0;
double *dd = new double[256];

//circular buffer
dd[aa] = 0.1;
for(int i = 0; i < 600; i++){
    qstr += QString::number(aa,'d',0) + "  " + QString::number(dd[aa],'f',1) + "         ";
    aa++;//onces 'aa' reaches 255, the next increment resets back to 0 for 'aa'
    dd[aa] = dd[aa - 1] + 1;
}

You have aa declared as unsigned char . 您有一个声明为unsigned char aa So when you hit 255 and increment, it goes back to 0. You should probably be using an int since this variable is used as an array index variable. 因此,当您达到255并递增时,它又回到0。您可能应该使用int,因为此变量用作数组索引变量。

It is because when aa increments by one from 255 it goes to 0 because of unsigned char , So it becomes dd[0] = dd[-1] + 1 now any junk can be present at dd[-1] and here it seems you have -1 . 这是因为当aa由一个从增量255它去0 ,因为unsigned char ,因此,它变成dd[0] = dd[-1] + 1现在任何junk可存在于dd[-1]和这里似乎你有-1

Also, you're accessing the array out of its bounds it is an undefined behavior. 另外,您正在访问数组的边界之外,这是未定义的行为。 You should try avoiding when aa becomes 0 . 您应该尝试避免当aa变为0

Unsigned char is 8 bit long. 无符号字符为8位长。 The maximum number that can be held by unsigned char is 255. (in binary 1111111). 无符号字符最多可容纳255。(二进制1111111)。 If you increment it by 1, it will become 0 如果将其增加1,它将变为0

I did casting to avoid the aa = -1: 我做了强制转换以避免aa = -1:

    dd[aa] = 0.1;
    for(int i = 0; i < 600; i++){
        qstr += QString::number((unsigned char)((unsigned char)aa-(unsigned char)1),'d',0) + "  " + QString::number(dd[aa],'f',1) + "         ";
        aa++;
        dd[aa] = dd[(unsigned char)((unsigned char)aa-(unsigned char)1)] + 1;  // casting
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM