compare with a 6-byte long string of zeros
in my code I work with Ethernet MAC addresses and need to compare for a 00:00:00:00:00:00 address; the easiest solution I came up with is this:
#define ETH_ADDR_LEN 6
unsigned char mac[ETH_ADDR_LEN] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 }; /* example */
const unsigned char empty[ETH_ADDR_LEN] = { 0, };
if (memcmp(mac, empty, ETH_ADDR_LEN) == 0) {
....
}
Is there a more concise way to achieve my goal? Simply memcmp(mac, "", 6) won开发者_Python百科't work -- may I know why?
Thanks in advance!
There is nothing wrong with your code. Keep it as it is. The "empty" array contains 6 zeroes so it will work just fine.
The memcmp(mac, "", 6)
does not work because the empty string consists of a single NUL character. Comparing 6 bytes will compare your MAC address against that NUL plus 5 bytes of potential garbage following it.
You can, however, force your string to contain six NUL characters using the following. Note that it only needs 5 explicit NULs because the string has an additional trailing NUL:
if(memcmp(mac, "\0\0\0\0\0", 6) == 0) {
...
}
memcmp(mac, "", 6)
does not work because ""
is an array of 1 character with zero value (and decays to a pointer to its single element).
Access to elements outside the array invoke Undefined Behaviour.
精彩评论