04-17-2013 08:38 AM - edited 04-17-2013 08:39 AM
Hello,
I noticed something strange when I try to initialize a char[] to hexadecimal values. When a value is more than 0x80 (0xBB in my example), it fills my array with extra 0x00 value. This does not happen when I declare my array as "unsigned char[]" or "static char[]".
Here is my code:
char array1[]={0x01,0x02,0x03,0xBB,0x05,0x06,0x07,0x08}; //prints as 01 02 03 BB 00 00 00 05 static char array2[]={0x01,0x02,0x03,0xBB,0x05,0x06,0x07,0x08}; //prints as 01 02 03 BB 05 06 07 08 unsigned char array3[]={0x01,0x02,0x03,0xBB,0x05,0x06,0x07,0x08}; //prints as 01 02 03 BB 05 06 07 08
Is this a normal behavior? I tested it with gcc and I got the same output (01 02 03 BB 05 06 07 08) for the 3 arrays.
Solved! Go to Solution.
04-17-2013 09:19 AM
I suppose the problem in array1 is that you are filling the array with a value bigger than it should be (infact you should receive a wanring in compilation: verify the checkbox Show build output window for warnings in Build options and check it if unchecked): as you can see in limits.h, max value for a (signed) char is 0x7f, while the unsigned char admits values up to 0xff.
I don't know exactly what is happening nor why the 'static' definition does not misfill the array, but both definitions return a warning that you should definitely avoid as it introduces an unpredictable behaviour in your program.
04-17-2013 09:31 AM
Thanks for this explanation. If I put "-0x45" instead of "0xBB" (same binary representation, but in the range of signed char), I have the correct output.
You are right about the warning, but when I turn on "Build with C99 extensions", I have only one warning on the "static char" declaration. If I turn off the option, I have the warning on "char[]" and "static char[]" declaration. That's why I didn't notice the problem at first.
Regards,