C标准库中没有内置函数可以执行此操作。这是滚动自己的简单方法:
int memrcmp(const void *s1, const void *s2, size_t n)
{
if(n == 0)
return 0;
// Grab pointers to the end and walk backwards
const unsigned char *p1 = (const unsigned char*)s1 + n - 1;
const unsigned char *p2 = (const unsigned char*)s2 + n - 1;
while(n > 0)
{
// If the current characters differ, return an appropriately signed
// value; otherwise, keep searching backwards
if(*p1 != *p2)
return *p1 - *p2;
p1--;
p2--;
n--;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果您具有高性能,则应该一次比较4个字节的字,而不是单个字节,因为内存延迟将成为瓶颈。但是,该解决方案要复杂得多,并不值得。