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

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

void printList(struct node *head);

int main() {
    struct node* head;
    head->data =10;
    head->next = NULL;
    printList(head);    
}


void printList(struct node *head){
    struct node *ptr = head;
    if (ptr->next = NULL){
        printf("list is empty");
    }
    while(ptr != NULL){
        printf("%d", ptr->data);
        ptr = ptr->next;
    }
}

I'm try to implement a simple list structure, but I am getting a segmentation error.

Any clues to why?

1
  • head->data = 10; : ask yourself the question: where does head point to? Did you read the chapter dealing with pointers and dynamic memory allocation in your learning material? Commented Dec 15, 2022 at 11:02

2 Answers 2

2

There are some issues with your code

  1. In main function, the head pointer is not initialized. You need to allocate memory for the object it will point to.
struct node* head = malloc(sizeof(struct node));
  1. In printList function, if statement using '=' assignment operator instead of '==' comparison operator
if (ptr->next == NULL){
    printf("list is empty");
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are different problems here. Check better about how pointers works in c.

When you write something like this struct node* head; you only added an address memory pointing to another undefined zone of space. So, in order to generate something you should alloc some memory in it before accessing that zone of memory and setting data.

Another problem is the first if condition in printList function that should have '==' instead of '='

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.