By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,844 Members | 1,889 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,844 IT Pros & Developers. It's quick & easy.

Why does my function give an error when I ran it?

P: 1
I'm writing a function that allows a user to create a singly linked-list I'm getting errors with the function. How can I fix this code?

Expand|Select|Wrap|Line Numbers
  1. struct node *createList(void)
  2. {
  3.     struct node *ptr, *tmp;
  4.     int classList, i, head, n;
  6.     head = (struct node *)malloc(sizeof(struct node));
  8.     if(head == NULL)
  9.     {
  10.         printf("Unable to locate list.");
  11.         exit(0);
  12.     }
  14.     printf("Enter total number of list: \n",);
  15.     scanf("%d", &classList);
  17.     head -> classList;
  18.     head -> next = NULL;
  19.     tmp = head;
  21.     for(i=2; i<=n; i++)
  22.     {
  23.         printf("Unable to allocate memory");
  24.         exit(0);
  25.     }
  27.     printf("Enter total number of list %d:", i);
  28.     scanf("%d", &classList);
  30.     ptr -> studentData = classList;
  31.     ptr -> next = NULL;
  32.     tmp -> next = ptr;
  33.     tmp = tmp -> next;
  35. }
2 Weeks Ago #1
Share this Question
Share on Google+
2 Replies

P: 60
What errors are you getting exactly? What case of insertion are you implementing? Insertion at end? beginning? or at a particular location?

For insertion at the end, a pointer variable (say ptr) should be made to point to the last node (done with the help of loop). Then, ptr-> next = node , where node->data is provided by the user and node->next is NULL.
2 Weeks Ago #2

Expert 100+
P: 2,396
It might help to see what struct node looks like.
It would really help if you told us what errors you're getting.

Here are a few issues that jumped out at me.
  1. Line 6: head should be a node* instead of an int.
  2. Line 17 doesn't do anything. What do you want it to do?
  3. Line 21: n is uninitialized. No way to predict if lines 23-24 execute or not.
  4. Lines 21-25: this block either does nothing or it prints an error message and exits.
  5. Lines 30-32: ptr is uninitialized.

You say you get errors when you run this program. I would have expected you to get compiler errors that prevent creation of a runnable program.
2 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.