1

I'm new in coding and I was wondering why this code crashes when I enter some value. There are some tutorials for this, but I don't get it.

Can someone explain linked lists very simple, please?

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

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

int main()
{
    tnode *head=NULL;
    tnode *new=(tnode*)malloc(sizeof(tnode));
    int d;
    scanf("%d", d);
    new->data=d;
    new->next=NULL;
    if(head==NULL)
    {
        head=new;
        return;
    }

    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

1

I saw a few problems in there, I think.

  1. This is not an error technically, but using new as an identifier (for a variable or method name) is not recommended. If one were to try to use this in a c++ program it would break.

  2. scanf("%d",d) should be scanf("%d",&d); it’s expecting the address of the variable where to store the input value.

  3. It doesn’t make much sense to return in the if statement, but if you do, you should specify a return code (your last return line has 0 as the code; you could use that, or pick a different number if you want).

owengall
  • 455
  • 4
  • 11