Search code examples
cpointerslinked-listoperations

Problems with valid pointers operations in C


In K&R, it says the valid pointers operations are assignment of pointes of the same type, adding or subtracting of the same array ......All other pointers arithmetic is illegal.

However, when i read the code of Doubly linked list on Wikipedia, it compares two pointers which points to different nodes of linked list. it confused me a lot. here is the code

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

it compares pFast and pCurrent, isn't it illegal.


Solution

  • According to N1570, there are no restrictions that two pointers to be compared have to be pointing at elements in the same array. What are pointed at by pFast and pCurrent are objects of the same type, so compareing them is legal.

    Quote from N1570 6.5.9 Equality operators:

    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.