1

我正在查看“search.h”C 库中“tfind”函数的源代码,我偶然发现了这一行:

#define DEREFNODEPTR(NP) (node)((uintptr_t)(*(NP)) & ~((uintptr_t) 0x1))

这是它的使用方式:

    /* Find datum in search tree.
   KEY is the key to be located, ROOTP is the address of tree root,
   COMPAR the ordering function.  */

void *
__tfind (const void *key, void *const *vrootp, __compar_fn_t compar)
{
  node root;
  node *rootp = (node *) vrootp;
  if (rootp == NULL)
    return NULL;
  root = DEREFNODEPTR(rootp);
  CHECK_TREE (root);
  while (DEREFNODEPTR(rootp) != NULL)
    {
      root = DEREFNODEPTR(rootp);
      int r;
      r = (*compar) (key, root->key);
      if (r == 0)
        return root;
      rootp = r < 0 ? LEFTPTR(root) : RIGHTPTR(root);
    }
  return NULL;
}

那么,为什么在这种情况下需要补码呢?

感谢您的时间和考虑。

4

1 回答 1

5

很可能实现假设节点指针指向始终至少 2 字节对齐的节点。这意味着对于有效的节点指针,最低有效位将始终为 0。这允许该位被“使用”来存储状态(例如它之前是否被访问过,或者它是红色还是黑色节点,或者其他一些东西......)。

宏在将值作为指针访问之前清除 LSB。没有人的补充要求。

于 2017-10-16T19:45:18.043 回答