Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C void pointers and pointer comparison

I have the following function to remove generic data from a linked list in C:

void removeData(void *data, struct accList *theList)
{
    struct accListNode* cur = theList->head;
    struct accListNode* prev = NULL;

    for(; cur != NULL; prev = cur, cur = cur->next)
    {
        if(cur->data == data)
        {
            if(cur == theList->head)
            {
               theList->head = cur->next;
            }
            if(cur == theList->tail)
            {
                theList->tail = prev;
            }
            if(prev != NULL)
            {
                prev->next = cur->next;
            }
            free(cur);
            return;
        }
    }
}

What is the meaning behind cur->data == data?

Since my data is generic (void*), what does this mean for any primitive type and any structure type?

For example, consider the employee structure:

struct employee
{
    char name[20];
    float wageRate;
};

How would the statement cur->data == data work if data is of type struct employee*? Since data is a pointer to the first memory address of the structure am I just comparing pointer addresses?

like image 477
CodeKingPlusPlus Avatar asked Sep 26 '26 07:09

CodeKingPlusPlus


2 Answers

cur->data == data

Compares the pointer cur->data to the pointer data. You're comparing their values, not their addresses. A pointer is a variable like any other. It has an address (i.e., &some_ptr) and a value (i.e., the address of the thing it refers to).

Note that other types of comparisons (i.e., < > >= <=) result in undefined behavior unless the pointers point to elements of the same array or one past the end (not that it would make sense to do so unless you knew they pointed to "objects" that resided in the same chunk of contiguous memory anyway, but still).

like image 122
Ed S. Avatar answered Sep 27 '26 19:09

Ed S.


What is the meaning behind cur->data == data?

The code is checking is both pointers are the same pointer

Since my data is generic (void*) what does this mean for any primitive type and any structure type?

How would the statement cur->data == data work if data is of type struct employee*?

Nothing, the comparison works the same

Since data is a pointer to the first memory address of the structure am I just comparing pointer addresses?

Nope, you're comparing pointers

like image 29
higuaro Avatar answered Sep 27 '26 21:09

higuaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!