0

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;
}
3
  • I don't know exacly, but maybe need cast in aa - 1 in last expression: dd[aa] = dd[static_cast< unsigned char >( aa - 1 )] + 1; - correct me, please, if I'm wrong but aa - 1 can be type int, not unsigned char, so you get memory access error. Aug 9, 2013 at 16:00
  • 1
    You are hoping that aa-1 will overflow back to 255. It doesn't, it is evaluated as an integer expression. The result will be -1. Aug 9, 2013 at 16:01
  • @Hans Passant, I did casting to avoid the -1 and it solved it thanks. Gave you a point.
    – jdl
    Aug 9, 2013 at 16:08

4 Answers 4

3

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.

4
  • aa is supposed to. But dd should not: dd[0] = dd[255] - 1 ... shouldn't it still grow?
    – jdl
    Aug 9, 2013 at 16:00
  • I want aa to cycle back around but dd should still be incrementting
    – jdl
    Aug 9, 2013 at 16:01
  • Well, for one thing you're indexing out of the dd array once aa wraps, since when aa = 0, you get dd[aa-1], which is dd[-1]. That means the behavior is undefined.
    – dcp
    Aug 9, 2013 at 16:05
  • I didn't down vote... but as Hans Passant said the issue is the evaluation is done as integer... so I casted it to (unsigned char) and it solved it... posted solution below.
    – jdl
    Aug 9, 2013 at 16:22
2

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.

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

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
    }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.