简体   繁体   English

此C代码的目的是什么?

[英]What is the purpose of this C code?

I was looking over the source code for the "tfind" function from the "search.h" C library and I stumbled upon this line: 我从“ search.h” C库中查看“ tfind”函数的源代码,但偶然发现了这一行:

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

This is how it's used: 使用方法如下:

    /* 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;
}

So, why is one's complement needed in this case? 那么,为什么在这种情况下需要补充?

Thank you for your time and consideration. 感谢您的时间和考虑。

It is likely the case that the implementation assumes the node pointers are to nodes that are always at least 2 byte aligned. 该实现有可能假设节点指针指向始终至少2个字节对​​齐的节点。 This means that the least significant bit will always be 0 for a valid node pointer. 这意味着对于有效的节点指针,最低有效位将始终为0。 This allows the bit to be "used" to store state (such as whether or not it has been visited before, or whether it is a red or black node, or some other thing...). 这允许“使用”该位以存储状态(例如,是否曾经访问过该位,或者它是否是红色或黑色节点,或其他某种东西……)。

The macro clears the LSB before accessing the value as a pointer. 宏在访问该值作为指针之前清除LSB。 There is no one's complement requirement. 没有补充的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM