I'm working on a program to verify RAID 6 data stripes, which involves loading an entire chunk from each disk into a memory array, then looking up each byte in a 256x256 LUT array to find the "Q syndrome."
I seem to be having some trouble with the nested dereference. I started out with the *(pointer + offset) syntax, but switched to the pointer[offset] syntax because I find it more readable. Both appear to produce the same result. Some values seem to be looked up correctly, some aren't, and some appear to work if I add 256 to the offset of the outer-most dereference, which isn't making sense.
Following is a minimized example of the problem - can anyone tell me what I'm doing wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main ()
{
char * Lut;
char * Data;
Lut = newchar [65536];
Data = newchar [786432];
Lut[192] = 157;
Data[0] = 192;
cout << Data[0]; //outputs 0xC0 (192) as expected
cout << Lut[192]; //outputs 0x9D (157) as expected
cout << Lut[Data[0]]; //outputs 0x00 instead of 0x9D (157)
delete[] Data;
delete[] Lut;
}
I started out with the *(pointer + offset) syntax, but switched to the pointer[offset] syntax because I find it more readable. Both appear to produce the same result.
Yes, they're equivalent by definition.
192 cannot be represented as a signed 8-bit value. If your computer uses two's complement arithmetic, (signed char)192 == -64.
I always use unsigned char when I want to use byte values precisely because of stupid crap like this.
That did it - thanks! Though I've used the char type before, I had no idea it was signed (seems silly to sign a single byte since it's called "char" and not "reallyshort int"). I've always assumed "unsigned char" was redundant and I guess the signed property has been hidden from me until now, since the bytes usually translate back and forth the same.
Edit: Apparently gcc makes chars signed by default, whereas other compilers do not. That probably better explains why I haven't run into this before (first time using gcc). gcc can take the argument "-funsigned-char" to make plain chars unsigned.
Technically, 'char' by itself can mean either 'signed char' or 'unsigned char' at the implementation's discretion. So if you specifically need one or the other you need to include signedness in the type name.
Every compiler I've seen makes char signed by default, though.