Char array truncation

Programming, for all ages and all languages.
Post Reply
User avatar
mark3094
Member
Member
Posts: 164
Joined: Mon Feb 14, 2011 10:32 pm
Location: Australia
Contact:

Char array truncation

Post by mark3094 »

Hi,

I have an array with scancodes in it. It is defined like this:

Code: Select all

ubyte keymap[128]
'ubyte' is just a typedef for 'unsigned char'
When I compile (VS 2010), I get this error:

Code: Select all

keymap.h(18): warning C4305: 'initializing' : truncation from 'int' to 'ubyte'
I'm reasonably sure this happens because there are escape codes, such as '\\' and '\'', and the compiler thinks I'm putting strings in the array.

It does work correctly, despite the warning. However, I would like a clean compile output. Is there a better way to do this, or is it best to just put up with the error?
User avatar
Love4Boobies
Member
Member
Posts: 2111
Joined: Fri Mar 07, 2008 5:36 pm
Location: Bucharest, Romania

Re: Char array truncation

Post by Love4Boobies »

Use uint8_t, don't typedef stuff like ubyte. As for the rest of your problem, http://www.catb.org/~esr/faqs/smart-questions.html (it describes precisely what you did wrong so don't get insulted and close the tab).
"Computers in the future may weigh no more than 1.5 tons.", Popular Mechanics (1949)
[ Project UDI ]
User avatar
mark3094
Member
Member
Posts: 164
Joined: Mon Feb 14, 2011 10:32 pm
Location: Australia
Contact:

Re: Char array truncation

Post by mark3094 »

Love4Boobies wrote:As for the rest of your problem, http://www.catb.org/~esr/faqs/smart-questions.html (it describes precisely what you did wrong so don't get insulted and close the tab).
Had a look, but it wasn't very useful.

The solution to the problem was a simple typo. Took quite a bit of looking into and testing before I even noticed it.
I had something like this:

Code: Select all

arr[2] = {'8', '9', '10'}
Which of course caused the problem, as you can only have one character per array element. I thought the compiler may have been mistaking the escape codes (eg, '\\') as multiple character, but of course it wasn't.

I hope this can be useful in some way to someone else, if only as a reminder that typos are sneaky!
User avatar
Love4Boobies
Member
Member
Posts: 2111
Joined: Fri Mar 07, 2008 5:36 pm
Location: Bucharest, Romania

Re: Char array truncation

Post by Love4Boobies »

http://www.catb.org/~esr/faqs/smart-que ... l#symptoms and http://www.catb.org/~esr/faqs/smart-que ... l#id478549 were the most important. The question was hence unanswerable. Remember that and maybe next time you can be helped.
"Computers in the future may weigh no more than 1.5 tons.", Popular Mechanics (1949)
[ Project UDI ]
Post Reply