简体   繁体   中英

circular buffer resets memory?

When this cycles back around dd[0] is set to 0 as apposed to 256.1 ?? It seems like 'dd' memory is resetting with 'aa' back to 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 . 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.

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 .

Also, you're accessing the array out of its bounds it is an undefined behavior. You should try avoiding when aa becomes 0 .

Unsigned char is 8 bit long. The maximum number that can be held by unsigned char is 255. (in binary 1111111). If you increment it by 1, it will become 0

I did casting to avoid the 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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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