user3739406
user3739406

Reputation: 364

Assignment from incompatible pointer type when using Linked Lists

I'm attempting to use a simple linked list example, in attempt to understand the basic idea behind using them, for later use. However, I've gotten confused about how to set each node in the list to a certain value. I.e here, I want to set member "a" to the address of "b" and member "b" to the address of c. However, this is where the warning occurs,

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

struct List
{
    int data;
    struct List * next;
};

int main (int argc, char * argv[])
{

    struct List * a = malloc(sizeof(struct List));
    a->data = 0;
    a->next = NULL;

    struct List * b = malloc(sizeof(struct List));
    b->data = 1;
    b->next = NULL;

    struct List * c = malloc(sizeof(struct List));
    c->data = 2;
    c->next = NULL;

    a->next = &b; //warning occurs here
    b->next = &c;
}

Is there a way to set the values of a->next (a.next) and b->next(b.next) without any warning whatsoever?

Upvotes: 1

Views: 302

Answers (2)

Steve Fallows
Steve Fallows

Reputation: 6424

b is already a pointer to a struct List so you don't need the & operator.

Just do:

a->next = b;

Upvotes: 0

flogram_dev
flogram_dev

Reputation: 42888

a->next is of type struct List *.

b is of type struct List *.

&b is of type struct List **.

You probably meant to do this: a->next = b;

Upvotes: 1

Related Questions