-1
struct node
{
int value;
struct node* nextptr;
};

typedef struct node Node;
typedef struct node* Nodeptr;

Nodeptr* currentptr = NULL;
Nodeptr* previousptr = NULL;
Nodeptr* startptr =NULL;

void insertnode(int data)
{

Nodeptr newptr;
newptr = (Nodeptr)malloc(sizeof(Node));
newptr->value = data;
newptr-> nextptr = NULL;

(*currentptr) = (Nodeptr)malloc(sizeof(Node));
(*previousptr) = (Nodeptr)malloc(sizeof(Node));
(*startptr) = (Nodeptr)malloc(sizeof(Node));

if((*currentptr) == NULL)
  {
   *currentptr = newptr;
   *startptr = newptr;
  }

else
{
  (*currentptr)->nextptr = newptr;
  *previousptr = *currentptr;
  (*currentptr) = newptr;
}
 }

This is the code that I'm using to create the linked lists.

 for(int i=0;i<n;i++)
 {
    int num;
    scanf("%d",&num);
    insertnode(num);
  }

This is used to get input from the user using a for loop.. int n is declared & initialized already. My program crashes after getting the first input. I have thought of memory allocation problems but that does not seem to resolve the problem. Also I'm new to C & programming so please excuse any tiny mistakes!

Rajesh Sri
  • 159
  • 1
  • 7
  • Why would `insertnode` have to create _four_ nodes to insert _one_?? – Paul Ogilvie Jan 10 '19 at 12:17
  • 1
    You want `Nodeptr currentptr = NULL` instead of `Nodeptr* currentptr = NULL` and `currentptr = (Nodeptr)malloc(sizeof(Node));` instead of `(*currentptr) = (Nodeptr)malloc(sizeof(Node));` etc. You typedefed `typedef struct node* Nodeptr`, this is poor practice and only adds confusion. There are most likely more problems though. – Jabberwocky Jan 10 '19 at 12:37
  • don't typedef pointer types (except function pointers) and [don't cast the result of `malloc` in C](https://stackoverflow.com/q/605845/995714) – phuclv Jan 10 '19 at 12:49

1 Answers1

0

from your code :

(*currentptr) = (Nodeptr)malloc(sizeof(Node));
...

if((*currentptr) == NULL)

Supposing you had memory to do the malloc and the assignment is valid, the test after is false and is useless

You have globally in your code a confusion between to get/set a pointer and to get/set the pointed value

My program crashes after getting the first input

Concerning your crash this is just because currentptr is null when you de-reference it in the first line above

There are plenty of examples of linked list in C on S.O. I encourage you to look at them using the search

If you have valgring use it, this a very useful tool, and/or of course use a debugger

bruno
  • 32,421
  • 7
  • 25
  • 37