Question

Hey,
I'm a beginner in C and tried to implement my own linked list implementation, that basically looks like this:

struct Element
{
    void *value;
    struct Element *next;
};

typedef struct
{
    struct Element *first;
    struct Element *last;
    unsigned int size;
} LinkedList;

void LinkedList_init(LinkedList *this)
{
    this->size = 0;
    this->first = NULL;
    this->last = NULL;
}

void LinkedList_add(LinkedList *this, void *value)
{
    struct Element *node = malloc(sizeof(struct Element));
    node->value = value;
    node->next = NULL;

    if (this->size == 0)
        this->first = this->last = node;
    else
    {
        this->last->next = node;
        this->last = node;
    }

    this->size++;
}

So in short, I want a linked list that can hold arbitrary types - I heard, this is possible in C by using void pointers. The problem now arises, when I want to use that implementation, for example with a structure as value:

typedef struct
{
    int baz;
} Foo;

int main(void)
{
    LinkedList list;
    Foo bar;
    bar.baz = 10;

    LinkedList_init(&list);
    LinkedList_add(&list, (void *) &bar);

    /* try to get the element, that was just added ... */
    Foo *firstElement = (Foo *)list.first;
    /* ... and print its baz value */
    printf("%d\n", firstElement->baz);

    return 0;
}

The last printf call just prints values like -1077927056, which look like a memory address. So it's probably a problem with pointers. After searching the web the last few days for a similar issue on the web (I had no luck with that), I tried to throw my own logic away and tested various random *& combinations. Turns out, that was a dead end, too. :(

It's probably something simple for a more experienced C programmer, but I just can't find the answer. Please help :D

Was it helpful?

Solution

list.fist is a struct Element.

Try:

Foo *firstElement = (Foo *)(list.first->value);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top