1

I am using a linked list defined as follows:

typedef struct {
    struct foo* next;
} foo;

Assuming that it has already been set up with the head pointer called linked_list and I want to iterate through the linked list as follows:

foo* curr = linked_list;
while(curr->next) {
    curr = curr->next;
}

My compiler (Clang) throws a warning about converting from struct foo* to foo* [-Wincompatible-pointer-types]

I know that I can suppress this warning by casting it, but is there a better way of doing this?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
dd.
  • 671
  • 1
  • 5
  • 13
  • 1
    Your code doesn't define `struct foo` anywhere. – melpomene Jul 21 '19 at 14:41
  • A general rule of thumb: Do not use `typedef`, as it mostly ever causes confusion. – alk Jul 21 '19 at 14:44
  • 1
    Your sense that "use a cast" is the wrong way to fix the problem is good – keep that sensitivity. Using casts is rarely the best way to fix a problem. Sometimes, it _is_ necessary — casts were created for a reason. But casts are too often applied in too many situations. They're dangerous. Using a cast claims "I know more than the compiler about C in this context", which is rarely the case. – Jonathan Leffler Jul 21 '19 at 14:47
  • The warning is legit: A struct foo* is not the same type as a pointer to foo (which is a typedef for struct { struct foo* next; }).... if you don’t care you can cast or use void* which will happily let you mix pointer-types. OR you could just use compatible pointers :)? – Morten Jensen Jul 21 '19 at 17:09

1 Answers1

0

The problem is that the structure struct foo used in this declaration

typedef struct {
    struct foo* next;
    ^^^^^^^^^^
} foo;

is never defined.

As result in this expression statement

curr = curr->next;

the left operand has the type foo * while the right operand has the type struct foo *.

Rewrite the structure definition the following way

typedef struct foo {
    struct foo* next;
} foo;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335