4 ms·
I can't see that working out the way they expect.
by bregma 6y ago
I can't see that working out the way they expect.
- Joker_vD 6y agoWell, on one hand, writing correct albeit slow memcmp() is easy, on the other hand, it has some gotchas... int my_memcmp(const void * ptr1, const void * ptr2, size_t num) { const unsigned char * p1 = ptr1; const unsigned char * p2 = ptr2; for (size_t i = 0; i < num; i++) { if p1[i] < p2[i] { return -1; } if p1[i] > p2[i] { return 1; } } return 0; } For example, technically speaking, unsigned char can be as wide as an int, so "p1[i] - p2[i]" may actually evaluate to unsigned int which is not what you want.
- MaxBarraclough 6y agoNitpick: those if statements need parentheses. > unsigned char can be as wide as an int, so "p1[i] - p2[i]" may actually evaluate to unsigned int which is not what you want Would this matter?
- wizzwizz4 6y agoI don't think it would; `<` and `>` aren't syntactic sugar in C.
- SomeoneFromCA 6y ago> unsigned char can be as wide as an int No, it is not true for almost all non-embedded systems. And char cannot be as wide as int, it is the opposite true, int can be as wide as char.
- saagarjha 6y agoint is guaranteed to be at least as wide as char.
- SomeoneFromCA 6y agoThis exactly what I was saying, just made a wrong choice of words.
- Joker_vD 6y ago"Int can be as wide as char" is exactly the same as "char can be as wide as int".
- SomeoneFromCA 6y agoI meant "int can be as narrow as char".