I'm reading MAC addresses (in standard hex notation, e.g. 00:11:22:33:44:55) from stdin and converting them into a 6 byte variable hw_addr as decimals:
u8 hw_addr[6];
scanf("%2x:%2x:%2x:%2x:%2x:%2x", &hw_addr[0], &hw_addr[1], &hw_addr[2], &hw_addr[3], &hw_addr[4], &hw_addr[5]);
The only problem is that I'm getting 6 scanf warnings:
warning: format '%2x' expects type 'unsigned int *', but argu开发者_运维知识库ment 3 has type 'u8 *'
.....
Any way to get rid of these warnings without wasting an int for each field?
According to my scanf
manpage,
hh Indicates that the conversion will be one of dioux or n and the next pointer is a pointer to a char (rather than int).
So you want "%2hhx:%2hhx:%2hhx:%2hhx:%2hhx:%2hhx"
Just use the right type
So you are using a machine that has billions of bytes of RAM and you want to save 6 of them?
If you are keeping an array of millions of mac addresses you should convert them to a packed format after reading them. But no harm is done by supplying canonical ints to scanf
().
For that matter, if hw_addr[]
is a local variable, then it effectively uses no space at all as it will be reused for other locals after your function returns.
Since you can't optimize everything, it is important to focus your optimization effort on things that really matter.
The warnings are an indication of a serious issue. You are passing pointers to unsigned bytes but the scanf function is going to be writing 32bits to those pointers. For the first 3 values, the extra 24 bits will overwrite parts of the hw_addr array, but for the last 3 values, you are overwriting some other variable on the stack.
To avoid a bad crash, at the very least you need to overallocate hw_addr
u8 hw_addr[6+3];
Will at least prevent your code from trashing the stack. But really, you should just be using the correctly sized values for scanf, and converting from ints back to unsigned bytes afterwards.
you are reading unsigned int into char address, this may not be very portable or safe. just use int array as a buffer to read and then copy to byte array
精彩评论