Is it okay to use characters as array subscripts?
My array is initialized to hold 256 objects, so it seems as though accessing out of bounds would not be an issue. But, I was getting some weird segmentation faults, which I found out were due to the fact that the character value that I was reading in was negative in some cases.
I don’t know how that is possible, however. Then, I casted it to an unsigned char, but that didn’t work either. I ended up getting boundary issues there as well. I also tried casting the char variables to ints and then accessing the array, but I still had segmentation issues.
What can I do to mitigate this? Being able to access the array via characters is nice because my program has an array cell for each character in the ASCII set. It seems to make sense, but I don’t know why its not working.
It’s perfectly valid to use values of character type as array indices. An array index can be of any integer type;
char,unsigned char, andsigned charare all integer types.But plain
charcan be either signed or unsigned, depending on the implementation. Either it has the same range assigned char, or it has the same range asunsigned char; either way, it’s still a distinct type.So if you have an array with 256 elements, you can safely index it with
unsigned char, which has a range of at least 0 to 255. You can’t safely index it withchar, since it could have negative values.I can’t help with that without more information.