Reputation: 6133
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.
Upvotes: 0
Views: 1110
Reputation: 835
Using an unsigned char should solve half the problem, although there's still another boundary issue that you need to be careful of. The other issue, is that your possibly accessing an element that is out of the maximum number of elements in the array. Here's an example:
char myArray[256];
myArray[0] = 0; // Works just fine
myArray[1] = 0; // Works just fine
myArray[256] = 0; // Segfaults
It segfaults because the program is trying to access a variable that is out of the bounds of the array (0 to 255). That's probably what's happening here, but I can't be sure without the code.
Upvotes: 0
Reputation: 263517
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
, and signed char
are all integer types.
But plain char
can be either signed or unsigned, depending on the implementation. Either it has the same range as signed char
, or it has the same range as unsigned 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 with char
, since it could have negative values.
Then, I casted it to an unsigned char, but that didn't work either. I ended up getting boundary issues there as well.
I can't help with that without more information.
Upvotes: 3