0

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

1 Answer 1

7

list.fist is a struct Element.

Try:

Foo *firstElement = (Foo *)(list.first->value);
Sign up to request clarification or add additional context in comments.

2 Comments

Argh, how simple :D But thank you very much for your time. This thing really kept bugging me.
...and the cast to (Foo *) is not necessary anymore, which should be a clue that this is on the right track.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.