1
struct list_node {
    int value;
    struct list_node *next;
};

struct linked_list {
    int size;
    struct list_node *head;
};

void print_linked_list(struct linked_list *list){
    struct linked_list *current = list;

    while(current != NULL){
        printf("%d ", current->head->value);
        current = current->head->next;
    }
}

I have to define a function to print out a linked list, but I get an error message saying "incompatible pointer type". I know that the problem is in "current = current->head->next;" but how can I achieve that?

1
  • 1
    You need struct list_node *curr = list->head; in place of struct linked_list *current = list;, and consequential changes in the loop (while (curr != NULL) { printf("%d ", curr->value); curr= curr->next; }). Commented Jan 17, 2022 at 14:25

2 Answers 2

3

current is a struct linked_list*, but current->head->next is a struct list_node*.

struct linked_list and struct list_node are two different unrelatd structures in spite of their similarity.

You cannot assign pointers to different types, hence the error message incompatible pointer type.

You probably want this:

void print_linked_list(struct linked_list* list) {
  struct list_node* current = list->head;

  while (current != NULL) {
    printf("%d ", current->value);
    current = current->next;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The function

void print_linked_list(struct linked_list *list){
    struct linked_list *current = list;

    while(current != NULL){
        printf("%d ", current->head->value);
        current = current->head->next;
    }
}

does not make a sense.

In this statement

current = current->head->next;

the pointer current has the type struct linked_list * while the expression current->head->next has the type struct list_node *.

It seems you mean

void print_linked_list( const struct linked_list *list )
{
    if ( list != NULL )
    {
        for ( const struct list_node *current = list->head; current != NULL; current = current->next )
        {
            printf( "%d ", current->value );
        }
    }
}

Comments

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.