Issue with linked list in c - c

I was trying out linked lists and for some reason it isnt doing what it is supposed to do. When I enter the quantity after choosing 1 it is all good until the node is add to the existing list, after which the quantity becomes a weird string of numbers. And also when ever i try adding more than one node to the donate list the program crashes.
EDIT: The above problem is solved but there is another problem which I forgot to mention
It is when I am trying to print the list out, nothing gets printed. This happens when I choose 4.
EDIT2: The print function is only printing out the first node nothing after that.
Please help.
Here's the code.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct donation{
char name[50];
int quant;
struct donation* next;
}donate;
donate* addItem(donate *mylist,donate *temp){
donate *front=(donate*)malloc(sizeof(donate*));
if(mylist==NULL)
return temp;
front=mylist;
while(mylist->next!=NULL)
mylist=mylist->next;
mylist->next=temp;
return front;
}
void print(donate* donList){
printf("Printing the Donations Table\n\n");
if(donList!=NULL){
while(donList->next!=NULL){
printf("%s %d\n",donList->name,donList->quant);
donList=donList->next;
}
}
}
main(){
donate *list=NULL;
while(1){
int choice;
printf("1. Add a donation\n);
printf("Enter your choice: ");
scanf("%d",&choice);
if(choice==1){
donate* temp=(donate*)malloc(sizeof(donate*));
printf("\nEnter inventory type: ");
scanf("%s",temp->name);
printf("Enter the amount: ");
scanf("%d",&temp->quant);
temp->next=NULL;
list=addItem(list,temp);
printf("\nDonation Added!\n");
printf("%s %d\n",list->name,list->quant);
}
else if(choice==4){
print(list);
}
}
system("pause");
return 0;
}
Thanks!

One problem is that you are mallocing space for a donate pointer. You need to allocate space for the struct itself.
donate* temp=(donate*)malloc(sizeof(donate*));
should be
donate* temp= malloc(sizeof(donate));
Since you are doing a malloc, prior to adding an item, I think addItem just needs to be:
donate* addItem(donate *mylist,donate *temp)
{
if (mylist != NULL)
temp->next = mylist;
return temp;
}
It looks like you would not print a 1 item list:
printf("Printing the Donations Table\n\n");
if(donList!=NULL){
printf("Not NULL!!!!\n");
while(donList->next!=NULL){
printf("%s %d\n",donList->name,donList->quant);
donList=donList->next;
}
}
I think it should be:
printf("Printing the Donations Table\n\n");
if (donList!=NULL)
{
printf("Not NULL!!!!\n");
do
{
printf("%s %d\n",donList->name,donList->quant)
donList=donList->next;
}
while(donList != NULL);
}

Try running your program linked to efence or with valgrind.
Both will tell you when and where things start to go bad.

There are two issue that I see. First is the issue pointed out by Scooter. Second is you have a memory leak in the first line of addItem().
Edit To answer your second question, you will need to fix the build error; you reference reqList in main() but never declare it.
Here is a corrected version of the code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct donation{
char name[50];
int quant;
struct donation* next;
}donate;
donate* addItem(donate *mylist,donate *temp){
if(mylist==NULL)
return temp;
donate *front=mylist;
while(mylist->next!=NULL)
mylist=mylist->next;
mylist->next=temp;
return front;
}
main(){
donate *list=NULL;
while(1){
int choice;
printf("1. Add a donation\n);
printf("Enter your choice: ");
scanf("%d",&choice);
if(choice==1){
donate* temp=(donate*)malloc(sizeof(donate));
printf("\nEnter inventory type: ");
scanf("%s",temp->name);
printf("Enter the amount: ");
scanf("%d",&temp->quant);
temp->next=NULL;
list=addItem(list,temp);
printf("\nDonation Added!\n");
printf("%s %d\n",list->name,list->quant);
}
}
system("pause");
return 0;
}

just make correction here
donate *front=(donate*)malloc(sizeof(donate*))
to
donate *front=(donate*)malloc(sizeof(donate))

Related

weird number appears on output-C

I have made a simple list like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
struct node{
int am;
struct node *next;
};
typedef struct node node;
int main(){
int n;
node *head=(node *)malloc(sizeof(node));
node *cur=head;
printf("Give me a number:\n");
scanf(" %d",head->am);
cur=head;
while(1){
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->am=n;
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
cur->next=null;
}
travel(head);
printf("Total nodes available :%d\n",count(head));
system("pause");
return 0;
}
Now travel is supposed to go through each node in the list and display the integer saved in each node.
void travel(node *h){
if(h==NULL)
return;
printf("Received data from node: \t %d\n",h->am);
travel(h->next);
}
Now the problem is that when travel is called it wont print the integer from the first node.It will also print another "Received data from node:" followed by a strange number.
For example
If i give 1,2,3,4 as inputs these are the results
Received data from node: 2
Received data from node: 3
Received data from node: 4
Received data from node: 4026432
Any ideas?
Now the problem is that when travel is called it wont print the
integer from the first node
This can be precisely known from this part of the main() function
printf("Give me a number:\n");
scanf(" %d",head->am); //this is wrong use of scanf("%d",&head->am);
cur=head;
while(1){
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->am=n;
as I've mentioned you're scanning wrongly but that doesn't matter because later in the code in while loop you replace it this way...
you scan number and store it at head->am
then you assign head to cur so head->am and cur->am are both the same now... so in while loop when you first assign n to cur->am, it gets assigned to head->am. so this explains why you never get to print first node.
Solution:
to overcome it ... in while loop, before assigning cur->am=n try doing:
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
//then... assign
curr->am=n;
this way you'll not lose first node.
suggestion:
As someone has already said it's much easier to traverse/ travel the list using loops (never mind... if you want to do it recursively)
here's how you do it with the loops:
void travel(node *h)
{
if(h==NULL)
return; //list is empty,consider printing "list empty" :)
while(h!=NULL)
{
printf("Received data from node: \t %d\n",h->am);
h=h->next;
}
}
To put all together your code without changing the travel() function as suggested would be:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int am;
struct node *next;
};
typedef struct node node;
void travel(node *h);
int main() //I have a habit of returning values from main() :)
{
int n;
node *head=(node *)malloc(sizeof(node));
node *cur=head;
printf("Give me a number:\n");
scanf(" %d",&head->am);
cur=head;
while(1)
{
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
cur->am=n; //NOTE:here's the change!
cur->next=NULL;
}
travel(head);
return 0; //just to signify successful compilation
}
void travel(node *h)
{
if(h==NULL)
return;
printf("Received data from node: \t %d\n",h->am);
travel(h->next);
}
Sample Input : 5 6 3 1 0
Sample Output :
Give me a number:
5
Give me a number
6
Give me a number
3
Give me a number
1
Give me a number
0
Received data from node: 5
Received data from node: 6
Received data from node: 3
Received data from node: 1
There are (at least) those issues:
The line scanf(" %d",head->am) is wrong since scanf() expects an address of the memory location of the expected value meaning &head->am.
Your loop scans a number and puts it in the current node and only after it creates a new node. Therefore, the first number you enter will be overridden (after fixing the first issue) and the last node created will contain random data because the loop will terminate after entering 0 but before putting anything in the last node.
I propose like this:
int main(void){
int n;
node anchor = {0, NULL};//dummy head
node *head, *cur = &anchor;
while(1){
printf("Give me a number\n");
scanf("%d", &n);
if(n==0)
break;
cur->next = malloc(sizeof(node));
cur = cur->next;
cur->am = n;
cur->next = NULL;
}
head = anchor.next;
travel(head);
printf("Total nodes available :%d\n", count(head));
return 0;
}
You are missing & at the first scanf:
scanf(" %d", &head->am);
But it could be made to do all the scanf inside the while:
int main(){
node *head=0;
node *cur=0;
node *prev=0;
while(1){
prev = cur;
cur=(node *)malloc(sizeof(node));
cur->next=NULL;
printf("Give me a number\n");
scanf("%d",&cur->am);
if(cur->am==0)
break;
if(head == NULL) head = cur;
if(prev != NULL) prev->next = cur;
}
travel(head);
printf("Total nodes available :%d\n",count(head));
return 0;
}
I hope I didnt make any mistake as I wrote it in this SO editor..
and as someone said, you should free the linked list .. but thats out of scope here..
HTH

not woking c program for SLL [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Q please help me this program is not working properly.
not displaying the value.this program is an example of singly linked list which I am trying to run on c.
`
#include<stdio.h>
#include<stdlib.h> //malloc defined
struct node
{
int data;
struct node *next;
};
add() //add function
{
int value;
struct node *n;
n=(struct node*)malloc(sizeof(struct node)); //mem allocation
printf("enter the value to add\n");
scanf("%d",&value);
n->data=value;
n->next=NULL;
// n=n->next;
// n->next=NULL;
}
delete() //delete function
{
// n=n->next;
struct node *n; //declaration
printf("the node deleted is %d",n->data);
free(n);
}
display() //display function
{
struct node *n;
while(n!=NULL)
{
printf("%d",n->data);
n=n->next;
}
}
int main()
{
int ch;
while(1)
{
printf("do you want to add node press 1\n");
printf("do you want to delete node press 2\n");
printf("do you want to display node press 3\n");
printf("do you want to exit press 4\n");
scanf("%d",&ch);
switch(ch)
{
case 1:add();
break;
case 2:delete();
break;
case 3:display();
break;
case 4:exit(0);
default: printf("wrong choice!!!\n");
}
}
return 0;
getch();
}
please help me this program is not working properly.
not displaying the value.this program is an example of singly linked list which I am trying to run on c.
printf("%d",n->data); is not printed because:
struct node *n; // n is not determined.
while(n != NULL) // undefined behaviour
n is different from the other n that is in the add() function. You never passed the struct to the other functions so it will not do what you wanted it to do.
in the function display(), the local variable 'n' is only declared but not defined, so here 'n' is only a wild pointer. It's happened in the function delete() as well.
it's not a correct way to implement the single linked list. In the function add() what you wrote is only create a node, but not add a node to linked list.
#include<stdio.h>
#include<stdlib.h> //malloc defined
struct node
{
int data;
struct node *next;
}*n,*p;
create() //add function
{
int value;
n=(struct node*)malloc(sizeof(struct node)); //mem allocation
printf("enter the value to add\n");
scanf("%d",&value);
n->data=value;
n->next=NULL;
}
add()
{
int value;
// struct node *p;
p=(struct node*)malloc(sizeof(struct node));
printf("enter the value to add next\n");
scanf("%d",&value);
n->next=p;
p->data=value;
p->next=NULL;
}
delete() //delete function
{
printf("the node deleted is %d",p->data);
n->next=NULL;
free(p);
}
display() //display function
{
while(n!=NULL)
{
printf("%d\n",n->data);
n=n->next;
}
}
int main()
{
int ch;
while(1)
{
printf("do you want to create node press 1\n");
printf("do you want to add node press 2\n");
printf("do you want to delete node press 3\n");
printf("do you want to display node press 4\n");
printf("do you want to exit press 5\n");
scanf("%d",&ch);
switch(ch)
{
case 1:create();
break;
case 2:add();
break;
case 3:delete();
break;
case 4:display();
break;
case 5:exit(0);
default: printf("wrong choice!!!\n");
}
}
return 0;
getch();
}

Function to read the data file as nodes in a linked list

My text file reads as this:
George Washington, 2345678
John Adams, 3456789
Thomas Jefferson, 4567890
James Madison, 0987654
James Monroe, 9876543
John Quincy Adams, 8765432
Andrew Jackson, 7654321
Martin Van Buren, 6543210
However, when I run my current code to display I don't get those numbers and end up with random ones, how can I fix this? You can avoid the other functions for now as I am just trying to make sure the file reads into different nodes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Creates node for holding student's information
struct node
{
char name [50];
int id;
struct node *next;
}*head;
//Create Function Prototypes
void readDataFile ();
void display(struct node *d);
void deleteID(int num);
void deleteName(char dname);
//Main function
int main()
{
//Declare variables
int i, num, intid;
char *name;
char nameDelete [50];
char nameInsert [50];
struct node *n;
//initialize link list
head = NULL;
//Read in file
readDataFile();
//Create list of operations utilized in program
while (1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Delete by ID\n");
printf("4.Delete by Name\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d", &i) <= 0)
{
printf("Enter only an Integer\n");
exit(0);
}
else
{
switch(i)
{
case 1:
printf("Enter the name to insert: ");
gets(nameInsert);
printf("Enter the ID associated with the name: ");
scanf("%d", &intid);
break;
case 2:
if (head == NULL)
printf("List is Empty\n");
else
{
printf("Elements in the list are:\n");
}
display(n);
break;
case 3:
if(head == NULL)
printf("List is Empty\n");
else
{
printf("Enter the ID number to delete: ");
scanf("%d", &intid);
}
break;
case 4:
if(head == NULL)
printf("List is Empty\n");
else
{
printf("Enter name to delete: ");
gets(nameDelete);
}
case 5:
return 0;
default:
printf("Invalid option\n");
}
}
}
return 0;
}
The problem you have is not the reading but the printing.
printf("Student %s has ID %d\n", d->name, &d->id);
You use the address-of operator & when reading with scanf (and family), but when you're printing it will print the address of the variable.
You also have some other problem with the reading of the file, besides what I mentioned in my comment, and that is your none-linking:
temp->next = malloc(sizeof(struct node));
temp = temp->next;
temp->next = NULL;
This will create an extra node at the end of the list, which will be uninitialized meaning that when you use the data it will lead to undefined behavior.
Actually, with the problem mentioned in my comment you will have two extra nodes.

Linked List Appcrash

I was trying to do an example about linked list. First, I added the values to the variables and there was no problem. But when I tried to get values from user, the program crashed when entering midterm 2 grade. I tried other input functions but the result is same. Where is the problem?
#include <stdio.h>
struct student
{
char *name;
int m1,m2,final;
struct student* next;
};
main()
{
addStudent();
system("PAUSE");
}
addStudent()
{
struct student *node = NULL;
struct student *firstnode;
firstnode = (struct student *)malloc(sizeof(struct student));
node = firstnode;
printf("press 0 to exit \n");
while(1)
{
printf("Student name: ");
scanf("%s", node->name)
if(node->name == "0") break;
printf("Midterm 1: ");
scanf("%d", node->m1);
printf("Midterm 2: ");
scanf("%d", node->m2);
printf("Final: ");
scanf("%d", node->final);
node->next = (struct student *)malloc(sizeof(struct student));
node = node->next;
}
node->next = NULL;
node = firstnode;
while(node->next);
while(node->next != NULL)
{
printf("%s - ",node->name);
printf("%d ", node->m1);
printf("%d ", node->m2);
printf("%d ", node->final);
node = node->next;
}
system("PAUSE");
return 0;
}
Fix 1
Remove the line
while(node->next);
Reason: It will put you on an infinite loop in most cases and it is unnecessary.
Fix 2
Replace the loop
while(node->next != NULL) {
}
with
if (node->next != NULL) {
while (node->next->next != NULL) {
}
}
Reason: You are allocating one additional struct each time and keeping it empty for reading next time. So the Linked List will end before the next becomes NULL.
Fix 3
Replace following in struct
char *name;
with
char name[80];
Reason: Memory not being allocated.
Fix 4
Replace at all occurrences of scanf (except for name)
scanf("%d", node->m1);
with
scanf("%d", &node->m1);
Reason: scanf needs memory location of data to be read.
Good luck
Your code has multiple errors.
To start with, the first scanf("%s", node->name) is missing its terminating semicolon.
Next, your function signatures are sloppy. main() should be int main(void). addStudent() should be int addStudent(void). (Or, get rid of its return 0 and let it return void.) Since you don't pre-declare addStudent(), you should define it before main() so that main() can know about it.
The crash, though, is because you haven't allocated memory for node->name. You've allocated memory for a node, but that doesn't give you space to put the name.

why isn't my code working?link list

q2 to demonstrate linked list operations:insertion,display & deletion//
the compiler code blocks is telling the two error at lines
73 and 83 which i have marked expected ; before'{' token
and expected declaration or statement at the end of the input*/
but it is also telling that in function create:
these two error are there !how is that possible when it is referring them to be in the main()
#include <stdio.h>
#include <stdlib.h>
struct list
{
int a;
char name[20];
int roll;
struct list *next;
};
struct list *create(struct list *ptr)
{
int v,n;
printf("\nenter the value of the inputs");
scanf("%d",&n);
struct list *temp;
printf("\ndo u want to continue(y/n)");
scanf("%d",&v);
while(1)
{
if(v=='y')
{
ptr=(struct list*)malloc(sizeof(struct list));
printf("\nenter the roll number of the student");
scanf("%d",&ptr->roll);
printf("\nenter the name of the student");
gets(ptr->name);
printf("\nenter the marks of the student");
scanf("%d",&ptr->a);
ptr->next=NULL;
}
else
if(v=='n')
{
break;
}
return(ptr);
}
}
void display(struct list *ptr)
{
struct list *temp;
temp=ptr;
while(temp!=NULL)
{
printf("\nthe roll number of the student is%d",temp->roll);
printf("\nthe name of the student is%d",temp->name);
printf("\nthe marks of the student is%d",temp->a);
temp=temp->next;
}
}
void del(struct list *ptr,int c)
{
struct list *temp;
struct list *gtemp;
gtemp=temp=ptr;
while(temp->roll!=c)
{
gtemp=temp;
temp=temp->next;
}
gtemp->next=temp->next;
free(temp);
}
main()
{ //73
struct list *ptr;
int c;
ptr=NULL;
ptr=create(ptr);
display(ptr);
printf("\nenter the value of roll number");
scanf("%d",&c);
del(ptr,c);
display(ptr);
}//83
regarding the first expected ; before'{' token error, instead of
main()
you should use the full signature
int main(int argc, char **argv)
for the second error, you should first indent your code properly.
check the {} combinations properly. you have mostly written display() function difination inside create{} function. so add the {} pairs properly. add keep code well indented
add one closing '}' before display() function defination.
and
printf("\nthe name of the student is%d",temp->name);
it should be %s for strings.

Resources