Search code examples
cansi-c

Why do I have to create a temporary reference to print something like: '(e1->next)->content' in C?


#include <stdio.h>
#include <stdlib.h>

typedef struct ListElemStruct {
     int content;
     ListElem next;
} *ListElem;

ListElem mkListElem(int content);

int main(void) {
    ListElem e1 = mkListElem(1);
    e1->next = mkListElem(2);
    
    printf("%d\n", e1->next->content);

    return 0;
}

ListElem mkListElem(int content) {
    ListElem new = calloc(1, sizeof(*ListElem));
    new->content = content;
    new->next = NULL;
    return new;
}

error messages:

c(6): warning undefined type or identifier (assuming int):_ListElem
c(13): warning different types in assignment (possibly loss of data)
c(13): warning assigning pointer type to non-pointer type
c(15): error _content not a member of _e1

It works, if I write it like this instead:

    ListElem tmp = e1->next;
    printf("%d\n", tmp->content);

I don't understand the issue here.

Why does the option with the 2 '->' operators not work and is there an easier way to print the content of the next ListElem instead of using a 'ListElem tmp'?


I understand now why the option with the 2 '->' operators doesn't work and have been told, that I should not reference ListElem in my ListElemStruct declaration at the top.

So how do i declare my ListElemStruct instead?


Solution

  • As elaborated in the comments (@Eric Postpischil, @dialer), the error was due to using ListElem before it was even declared. This caused the Virtual-C compiler to assume that next was an ìnt, which was then implicitly cast to the correct type with ListElem tmp = e1->next;.

    Solution for a better way to write my ListElemStruct (provided by @Eric Postpischil):

    typedef struct ListElemStruct {
        int content;
        struct ListElemStruct *next;
    } *ListElem;