redixhumayun
redixhumayun

Reputation: 1864

LinkedList in C error

I am attempting to write a LinkedList in C. Here are my two structs

struct node{
  int key;
  int value;
  struct node *next;
};

struct LinkedList {
  struct node *head;
};

And here is how I create a new node.

void createNode(int key, int value) {
  struct node *new_node;
  new_node->key = key;
  new_node->value = value;
  new_node->next = lList->head;
  lList->head = new_node;
}

I am trying to traverse through the LinkedList using the function below.

void traverseNode(struct LinkedList *lList) {
  struct node current = *lList->head;
  while(current != NULL) {
    printf("%i", current->key);
    current = current->next;
  }
}

However, I keep getting an error saying

invalid operands to binary expression ('struct node'
      and 'void *')

in relation to my while expression.

Also, I get an error for the

printf("%i", current->key);
current = current->next

with the error being

member reference type 'struct node' is not a pointer; maybe you meant to use '.'

I am confused because I thought in my node struct, the *next was defined as a pointer and could therefore be accessed only using the indirection(->) syntax.

I am a beginner to pointers, so any help is appreciated.

Upvotes: 0

Views: 493

Answers (4)

kocica
kocica

Reputation: 6465

You cant compare NULL with non-pointer type.

Declare variable current as pointer + remove dereference of head and it will compile

struct node * current = lList->head;
            ^          ^
while(current != NULL)  // Now you can compare them

You are getting SEGFAULT because you are dereferencing uninitialized pointer. Allocate enough memory on heap (dynamic storage duration).

struct node *new_node = malloc(sizeof(struct node));

Since current is pointer

printf("%i", current->key);
current = current->next;

should be OK now.

Upvotes: 2

Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40247

void createNode(int key, int value) {
  struct node *new_node; // you need to malloc here
  new_node->key = key;
  new_node->value = value;
  new_node->next = lList->head;
  lList->head = new_node;
}

You must malloc before access a pointer.

struct node *new_node = (struct node*)malloc(sizeof(struct node));

Also change like,

struct node current = *lList->head;

into,

struct node *current = *lList->head;

Upvotes: 0

aatate98
aatate98

Reputation: 11

do{
printf("%i", current->key);
current = current->next;
} while(current != NULL)

doing this instead will check if your on the last node by seeing if the next node is null rather than the whole structure

Upvotes: 1

0___________
0___________

Reputation: 67855

As the error states current is a structure, not the pointer

change it to struct node *current = lList -> head;

remember that pointer itself does not have the storage for the referenced object

Upvotes: 2

Related Questions