c - C 中有效指针操作的问题

标签 c pointers linked-list operations

在K&R中,它说有效的指针操作是相同类型指针的赋值,相同数组的加或减......所有其他指针运算都是非法的。

但是,当我在维基百科上阅读双向链表的代码时,它比较两个指向链表不同节点的指针。这让我很困惑。 这是代码

    unsigned int DetectCycleinList(void)
    {
        DoublLinkedList* pCurrent = pHead;
        DoublLinkedList* pFast = pCurrent;
        unsigned int cycle = FALSE;
        while ((cycle == false) && pCurrent->pNext != NULL)
        {
            if (!(pFast = pFast->pNext))
            {
                cycle = false;
                break;
            }
            else if (pFast == pCurrent)
            {
                cycle = true;
                break;
            }
            else if (!(pFast = pFast->pNext))
            {
                cycle = false;
                break;
            }
            else if (pFast == pCurrent)
            {
                cycle = true;
                break;
            }
            pCurrent = pCurrent->pNext;
        }
    }

比较pFast和pCurrent,是不是不合法。

最佳答案

根据 N1570 , 没有限制要比较的两个指针必须指向同一数组中的元素。 pFastpCurrent指向的是同一类型的对象,所以比较是合法的。

引自 N1570 6.5.9 等式运算符:

Constraints

2 One of the following shall hold:
— both operands have arithmetic type;
— both operands are pointers to qualified or unqualified versions of compatible types;
— one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or
— one operand is a pointer and the other is a null pointer constant.

[...]

6 Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.

关于c - C 中有效指针操作的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596812/

相关文章:

c++ - 什么是智能指针,我应该什么时候使用它?

c - VLA 和通过 malloc 进行的动态内存分配有什么区别?

java - 删除插入到作为队列实现的 LinkedList 中的任何对象

c - 为什么我添加了多个节点,但我的链表只包含一个节点?

c - 如何分配内存并用指向二维数组的指针填充结构

c - free(malloc(m)) 的空间复杂度

c - 无法在/usr/share中创建目录

c - printf 不打印

pointers - Rust 的 Arc 和 Rc 类型与垃圾收集有何不同?

用于链接列表的 Mergesort 的 Python 实现不起作用