Reputation: 6321
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;
}
Upvotes: 0
Views: 125
Reputation: 6321
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
}
Upvotes: 0
Reputation: 5325
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
.
Upvotes: 2
Reputation: 979
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
Upvotes: 0
Reputation: 55449
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.
Upvotes: 3