Link List, Jamming Console - c

When i compile this link list my Console Jams after entering the first two intergers. The purpose of the programme is to save the input from scanf into Memory and then output them onto the screen, after this i intend to have the programme save the inputs into a text file.
#include <stdio.h>
#include <stdlib.h>
/*********************************************************
* Node to represent a packet which includes a link reference*
* a link list of nodes with a pointer to a packet Struct *
**********************************************************/
struct Packet {
unsigned int Source;
unsigned int Destination;
unsigned int Type;
unsigned int Port;
char *Data;
struct Packet *next;
};
typedef struct Packet node; // Removes the need to constantly refer to struct
/*********************************************************
* Stubs to fully declared functions below *
**********************************************************/
void Outpacket(node **head);
void push(node **head, node **aPacket);
node* pop(node **head);
int main() {
/*********************************************************
* pointers for the link list and the temporary packeyt to *
* insert into the list *
**********************************************************/
node *pPacket, *pHead = NULL;
/*********************************************************
* Create a packet and also check the HEAP had room for it *
**********************************************************/
pPacket = (node *)malloc(sizeof(node));
if (pPacket == NULL)
{
printf("Error: Out of Memory\n");
exit(1);
}
printf("Enter Source Number:\n");
scanf("%i", pPacket->Source);
printf("Enter Destination Number:\n");
scanf("%i", pPacket->Destination);
printf("Enter Type Number:\n");
scanf("%i", pPacket->Type);
printf("Enter Port Number:\n");
scanf("%i", pPacket->Port);
printf("Enter Data Number:\n");
scanf("%c", pPacket->Data);
pPacket->next = NULL;
/*********************************************************
* Push the Packet onto the selected Link List, the function *
* is written so the program will support multiple link *
* list if additional 'pHead' pointers are created. *
* *
**********************************************************
* NOTE: The push parameters are using references to the *
* pointers to get round the pass by value problem caused *
* by the way C handles parameters that need to be *
* modified *
**********************************************************/
push(&pHead, &pPacket);
pPacket = (node *)malloc(sizeof(node));
if (pPacket == NULL)
{
printf("Error: Out of Memory\n");
exit(1);
}
printf("Enter Source Number:\n");
scanf("%i", pPacket->Source);
printf("Enter Destination Number:\n");
scanf("%i", pPacket->Destination);
printf("Enter Type Number:\n");
scanf("%i", pPacket->Type);
printf("Enter Port Number:\n");
scanf("%i", pPacket->Port);
printf("Enter Data Number:\n");
scanf("%c", pPacket->Data);
pPacket->next = NULL;
push(&pHead, &pPacket);
/*********************************************************
* Display the Link List 'pHead' is passed as a reference *
**********************************************************/
Outpacket(&pHead);
if(pPacket = pop(&pHead))
{
printf("pPacket %s\n", pPacket->Data);
free(pPacket);
};
Outpacket(&pPacket);
while(pPacket = pop(&pHead)) {
free(pPacket);
}
return 0;
}
void Outpacket(node **head)
{
/*********************************************************
* Copy Node pointer so as not to overwrite the pHead *
* pointer *
**********************************************************/
node *pos = *head;
printf("Packet list\n");
/*********************************************************
* Walk the list by following the next pointer *
**********************************************************/
while(pos != NULL) {
printf("Source: %i Destination: %i Type: %i Data: %i \n", pos->Source, pos->Destination, pos->Type, pos->Data, pos->next);
pos = pos->next ;
}
printf("End of Packet\n\n");
}
void push(node **head, node **aPacket)
{
/*********************************************************
* Add the cat to the head of the list (*aCat) allows the *
* dereferencing of the pointer to a pointer *
**********************************************************/
(*aPacket)->next = *head;
*head = *aPacket;
}
node *pop(node **head)
{
/*********************************************************
* Walk the link list to the last item keeping track of *
* the previous. when you get to the end move the end *
* and spit out the last Packet in the list *
**********************************************************/
node *curr = *head;
node *pos = NULL;
if (curr == NULL)
{
return NULL;
} else {
while (curr->next != NULL)
{
pos = curr;
curr = curr->next;
}
if (pos != NULL) // If there are more packets move the reference
{
pos->next = NULL;
} else { // No Packets left then set the header to NULL (Empty list)
*head = NULL;
}
}
return curr;
}
Thanks

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct Packet {
unsigned int Source;
unsigned int Destination;
unsigned int Type;
unsigned int Port;
char *Data;
struct Packet *next;
};
typedef struct Packet* node;
node getnode(void){
node p;
p=malloc(sizeof(struct Packet));/*change1*/
return p;
}
void Outpacket(node *head);
void push(node *head, node *aPacket);/*change 2*/
node pop(node *head);
int main() {
node pPacket = NULL;
node pHead = NULL;
pPacket = getnode();/*change 3*/
if (pPacket == NULL)
{
printf("Error: Out of Memory\n");
exit(1);
}
printf("Enter Source :\n");
scanf("%d", &(pPacket->Source));
printf("Enter Destination Number:\n");
scanf("%d", &(pPacket->Destination));
printf("Enter Type Number:\n");
scanf("%d", &(pPacket->Type));
printf("Enter Port Number:\n");
scanf("%d", &(pPacket->Port));
printf("Enter Data Number:\n");
pPacket->Data=malloc(100);/*change 4,might overflor,so you decide how much memory you want*/
scanf("%s",pPacket->Data);
pPacket->next = NULL;
push(&pHead, &pPacket);
pPacket = getnode();/*change 5*/
if (pPacket == NULL)
{
printf("Error: Out of Memory\n");
exit(1);
}
printf("Enter Source Number:\n");
scanf("%d", &(pPacket->Source));
printf("Enter Destination Number:\n");
scanf("%d", &(pPacket->Destination));
printf("Enter Type Number:\n");
scanf("%d", &(pPacket->Type));
printf("Enter Port Number:\n");
scanf("%d", &(pPacket->Port));
printf("Enter Data Number:\n");
pPacket->Data=malloc(100);/*change 6*/
scanf("%s",pPacket->Data);
pPacket->next = NULL;
push(&pHead, &pPacket);
Outpacket(&pHead);
if(pPacket == pop(&pHead))/*change 7,this was a classic error*/
{
printf("pPacket %s ", pPacket->Data);
free(pPacket);
}
Outpacket(&pPacket);
while(pPacket == pop(&pHead))/*change 8,again the same error,please take care of this*/{
free(pPacket);
}
getch();
return 0;
}
void Outpacket(node *head)
{
node pos = *head;
printf("Packet list\n");
while(pos != NULL) {
printf("Source: %d Destination: %d Type: %d Data: %s \n", pos->Source, pos->Destination, pos->Type,pos->Data);/*change 9,what you wrote was absurd, I think*/
pos = pos->next ;
}
printf("End of Packet\n\n");
}
void push(node *head, node *aPacket)
{
(*aPacket)->next = *head;
*head = *aPacket;
}
node pop(node *head)
{
node curr = *head;
node pos = NULL;
if (curr == NULL)
{
return NULL;
} else {
while (curr->next != NULL)
{
pos = curr;
curr = curr->next;
}
if (pos != NULL)
{
pos->next = NULL;
} else {
*head = NULL;
}
}
return curr;
}
This code runs on my machine perfectly.Please Review the changes and compare both the codes,ask me if you don't understand any change.

Related

Cannot access memory at address at address "" (gdb)

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct Node {
/* Data fields with appropraiate types */
char fname[64];
char lname[64];
char puid[16];
int Age;
struct Node *next;
};
struct List {
struct Node *start;
int numNodes;
};
struct List * initialize_list() {
struct List *list = (struct List *) malloc(sizeof(struct List *));
list -> numNodes = 0;
list -> start = (struct Node *) malloc(sizeof (struct Node *));
return list;
}
struct List * CreateList() {
struct List *list = initialize_list();
return list;
}
void Traverse(struct List *list) {
struct Node *node = (struct Node *) malloc (sizeof(struct Node));
int i = 1;
node = list -> start -> next;
while (node != NULL) {
printf ("\nNode: %d", i);
printf("\nPUID: %s", node -> puid);
node = node -> next;
i++;
}
if (i == 1) {
printf("\n\nEmpty List");
}
}
struct Node *CreateNode(char first_name[], char last_name[], char PUID[], int age) {
struct Node *newNode = (struct Node *) malloc (sizeof(struct Node *));
strcpy(newNode->fname, first_name);
strcpy(newNode->lname, last_name);
strcpy(newNode->puid, PUID);
newNode->Age = age;
newNode->next = NULL;
return newNode;
}
void InsertFront(struct List *list, char first_name[], char last_name[], char PUID[], int age) {
struct Node *newNode = CreateNode (first_name, last_name, PUID, age);
if (list -> numNodes == 0) {
list -> start -> next = newNode;
list -> numNodes++;
return;
}
newNode -> next = list -> start -> next;
list -> start -> next = newNode -> next;
list -> numNodes++;
return;
}
int main () {
struct List *myList = CreateList();
while (1) {
int option = 0;
char fname[64];
char lname[64];
char puid[16];
int age;
printf("\n0. Exit Program \n1. Insert Front\n2. Insert Middle\n3. Insert End\n4. Delete Front\n5. Delete Middle\n6. Delete End\n7. Traverse \n8. Look Up by Index\n");
printf ("Enter option: ");
option = getchar();
if (option == '0') {
exit (0);
}
else if (option == '1' || option == '2' || option == '3') {
printf("Enter first name: ");
scanf("%s", fname);
printf("Enter last name: ");
scanf("%s", lname);
printf("Enter PUID: ");
scanf("%s", puid);
printf("Enter age: ");
scanf("%d", &age);
if (option == '1') {
InsertFront (myList, fname, lname, puid, age);
}
else if (option == '2') {
int index;
printf ("Enter position to Insert: ");
scanf ("%d", &index);
InsertMiddle (myList, index, fname, lname, puid, age);
}
else if (option == '3') {
InsertEnd (myList, fname, lname, puid, age);
}
}
else if (option == 4) {
}
else if (option == 5) {
}
else if (option == 6) {
}
else if (option == '7') {
Traverse (myList);
}
else if (option == 8) {
}
else {
}
getchar();
}
return 0;
}
I'm relearning some of this but I'm not sure where I'm going wrong.
I get a segmentation fault when the program reaches the Traverse() function.
I can access the Node that before the iteration of the while loop is not complete. As soon as the next iteration begins the myList -> start -> next can't be accessed any longer.
In Create node method:
malloc (sizeof(struct Node *))
Will allocate only 4 or 8 bytes because it sizeof pointer.
It should be:
malloc (sizeof( Node ))
to allocate space for an object

Error while printing the linked list

I created the linked list to store employee id and name.
When I tried to print it, it shows only id not an employee name and i also want to exit the program when the user enter -1 and not asking the name its should simply exit the program and display the id and name i am currently using devC++ for compiling my code
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int id;
char name[20];
struct node *next;
};
struct node *create()
{
struct node *p, *r, *n;
int s, k;
char name[20];
s = sizeof(struct node);
printf("Linked List\n");
printf("Enter id:");
scanf("%d", &k);
printf("Enter name:");
scanf("%s", name);
p = r = NULL;
while(k!=-1)
{
n = (struct node *)malloc(s);
n->id = k;
n->next = NULL;
if(r == NULL)
r = n;
else
p->next=n;
p=n;
printf("Enter the Id or-1 to stop:");
scanf("%d", &k);
printf("Enter the name ");
scanf("%s", name);
}
return(r);
}
void display(struct node *r)
{
printf("\nId Name \n");
while(r != NULL)
{
printf("\n %d", r->id);
printf("\n %s", r->name);
r = r->next;
}
}
int main()
{
struct node *ptr;
ptr = create();
display(ptr);
}
You actually read in the name variable, but you don't move it in your structure.
That said, you could directly read into the structure you allocate, but the tricky part is taking care of not overflowding your buffer when the user input is too big (more than 19 chars).
This could look like this:
#include<stdio.h>
#include<stdlib.h>
struct node {
int id;
char name[20];
struct node *next;
};
struct node *create(void) {
struct node *p, *r;
printf("Linked List\n");
p = r = NULL;
while (1) {
int id;
printf("Enter the Id or-1 to stop:");
scanf("%d", &id);
if (id == -1)
break; // user asked to leave
struct node *n = malloc(sizeof(*n));
// if (n == NULL) exit(-1); as you prefere...
n->id = id;
printf("Enter the name ");
// careful of buffer overflow here
scanf("%19s%*[^\n]", n->name);
n->next = NULL;
if (r == NULL)
r = n;
else
p->next = n;
p = n;
}
return r;
}
void delete(struct node *r) {
while (r != NULL) {
struct node *n = r;
r = r->next;
free(n);
}
}
void display(const struct node *r) {
printf("\nId Name \n");
while (r != NULL) {
printf("%d %s\n", r->id, r->name);
r = r->next;
}
}
int main(int argc, char **argv) {
struct node *ptr = create();
display(ptr);
delete(ptr);
return 0;
}
As a bonus, I also added the free part so that you don't leak.

How to pass a linked list to a function in C

So I have made a working program for getting data from a file and printing out the file according to which part of the file you want all within main. But my goal is to make this modular, by creating a user interface and either appending to the linked list from the file or printing out a part of that linked list (if any) as requested.
There's just one problem: I can't seem to figure out a way to successfully pass a linked list to the function so that when you create new nodes in the function (Append), it will also work in main and then back again in (Print).
Here's the working code:
#include <stdio.h>
#include <stdlib.h> /* has the malloc prototype */
#define TSIZE 100 /* size of array to hold title */
struct book {
char title[TSIZE], author[TSIZE],year[6];
struct book * next; /* points to next struct in list */
};
//typedef struct book ITEM;
typedef struct book * Node; // struct book *
void Append(Node *List, Node *Lcurrent,char filename[]);
void ClearGarbage(void);
int main(void){
Node head=NULL;
Node current;
current=head;
char fname[]="HW15Data.txt";
char op;
do{
puts("Select operation from the following list:");
puts("a. Append p. Print q. quit");
op = getchar();
ClearGarbage();
if (op=='a'){
/* Gather and store information */
Append(&head,&current,fname);
}
else if (op=='q'){
/* User quit, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Bye!\n");
return 0;
}
else{
/* Program done, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Invalid characted entered. Bye!\n");
return 0;
}
} while (op!='q');
return 0;
}
void Append(Node *List, Node * Lcurrent,char filename[TSIZE]){
FILE * fp;
Node head=*List;
Node current=*Lcurrent;
int loops=0;
fp=fopen(filename,"r");
if (head==NULL){
head=(Node) malloc(sizeof(struct book));
current=head;
current->next=NULL;
}
do{
current->next = (Node) malloc(sizeof(struct book));
current=current->next;
loops++;
} while(fgets(current->title,sizeof(current->title),fp) && fgets(current->author,sizeof(current->title),fp) && fgets(current->year,sizeof(current->year),fp));;
free(current);
printf("Number of records written: %d\n",loops);
//Same as Print function in the nonworking code
int num;
int i=0;
if (head == NULL){
printf("No data entered. ");
}
else{
printf("Enter record # to print: ");
scanf("%d",&num);
ClearGarbage();
num=num+1;
current = head;
while (current != NULL && i<num)
{
for (i=0;i<num;i++)
current = current->next;
printf("Book: %sAuthor: %sYear: %s\n",
current->title, current->author, current->year);
}
}
}
void ClearGarbage(void){
while (getchar()!='\n');
}
Okay cool that works, but my guess is that as soon as Append is done, the nodes made in Append are useless in main because they are now gone. So when I try to make a Print function in the following code, there's nothing to print.
#include <stdio.h>
#include <stdlib.h> /* has the malloc prototype */
#define TSIZE 100 /* size of array to hold title */
struct book {
char title[TSIZE], author[TSIZE],year[6];
struct book * next; /* points to next struct in list */
};
//typedef struct book ITEM;
typedef struct book * Node; // struct book *
void Append(Node *List, Node *Lcurrent,char filename[]);
int Print(Node *List,Node *Lcurrent);
void ClearGarbage(void);
int main(void){
Node head=NULL;
Node current;
current=head;
char fname[]="HW15Data.txt";
char op;
do{
puts("Select operation from the following list:");
puts("a. Append p. Print q. quit");
op = getchar();
ClearGarbage();
if (op=='a'){
/* Gather and store information */
Append(&head,&current,fname);
}
else if (op=='p'){
/*Print book record of user's choice*/
Print(&head,&current);
}
else if (op=='q'){
/* User quit, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Bye!\n");
return 0;
}
else{
/* Program done, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Invalid characted entered. Bye!\n");
return 0;
}
} while (op!='q');
return 0;
}
void Append(Node *List, Node * Lcurrent,char filename[TSIZE]){
FILE * fp;
Node head=*List;
Node current=*Lcurrent;
int loops=0;
fp=fopen(filename,"r");
if (head==NULL){
head=(Node) malloc(sizeof(struct book));
current=head;
current->next=NULL;
}
do{
current->next = (Node) malloc(sizeof(struct book));
current=current->next;
loops++;
} while(fgets(current->title,sizeof(current->title),fp) && fgets(current->author,sizeof(current->title),fp) && fgets(current->year,sizeof(current->year),fp));
free(current);
printf("Number of records written: %d\n",loops);
}
int Print(Node *List,Node *Lcurrent){
int num;
int i=0;
Node head=*List;
Node current=*Lcurrent;
if (head == NULL){
printf("No data entered.\n");
return -1;
}
printf("Enter record # to print: ");
scanf("%d",&num);
ClearGarbage();
num=num+1;
current = head;
while (current != NULL && i<num)
{
for (i=0;i<num;i++){
current = current->next;
}
printf("Book: %sAuthor: %sYear: %s\n",
current->title, current->author, current->year);
}
return 0;
}
void ClearGarbage(void){
while (getchar()!='\n');
}
Thanks anyone for any help!
EDIT: Got rid of an unused typedef for clarity
It seems like most of the people are focusing the lack of organization (it bother me a lot too) instead of your actual issue.
Seems like the source of your issue is where you assign the variable head.
when you define "Node head = *List" and List is NULL, as it's first initialized, it loses the connection it had to the original list you sent from main, and you just create a linked list with a local reference only.
I just changed the uses of "head" to "*List" within the Append and Print functions and it seems to sort it out.
This is your code after my changes:
#include <stdio.h>
#include <stdlib.h> /* has the malloc prototype */
#define TSIZE 100 /* size of array to hold title */
struct book {
char title[TSIZE], author[TSIZE], year[6];
struct book * next; /* points to next struct in list */
};
//typedef struct book ITEM;
typedef struct book * Node; // struct book *
void Append(Node *List, Node *Lcurrent, char filename[]);
int Print(Node *List, Node *Lcurrent);
void ClearGarbage(void);
int main(void) {
Node head = NULL;
Node current;
current = head;
char fname[] = "HW15Data.txt";
char op;
do {
puts("Select operation from the following list:");
puts("a. Append p. Print q. quit");
op = getchar();
ClearGarbage();
if (op == 'a') {
/* Gather and store information */
Append(&head, &current, fname);
}
else if (op == 'p') {
/*Print book record of user's choice*/
Print(&head, &current);
}
else if (op == 'q') {
/* User quit, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Bye!\n");
return 0;
}
else {
/* Program done, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Invalid characted entered. Bye!\n");
return 0;
}
} while (op != 'q');
return 0;
}
void Append(Node *List, Node * Lcurrent, char filename[TSIZE]) {
FILE * fp;
Node head = *List;
Node current = *Lcurrent;
int loops = 0;
char line[256];
fp = fopen(filename, "r");
if (*List == NULL) {
*List = (Node)malloc(sizeof(struct book));
current = *List;
current->next = NULL;
}
do {
current->next = (Node)malloc(sizeof(struct book));
current = current->next;
loops++;
} while (fgets(current->title, sizeof(line), fp) && fgets(current->author, sizeof(line), fp) && fgets(current->year, sizeof(line), fp));
free(current);
printf("Number of records written: %d\n", loops);
}
int Print(Node *List, Node *Lcurrent) {
int num;
int i = 0;
Node head = *List;
Node current = *Lcurrent;
if (*List == NULL) {
printf("No data entered.\n");
return -1;
}
printf("Enter record # to print: ");
scanf("%d", &num);
ClearGarbage();
num = num + 1;
current = *List;
while (current != NULL && i<num)
{
for (i = 0; i<num; i++) {
current = current->next;
}
printf("Book: %sAuthor: %sYear: %s\n",
current->title, current->author, current->year);
}
return 0;
}
void ClearGarbage(void) {
while (getchar() != '\n');
}
There are still many logical errors, and some bugs, but it fixes the problem you asked help for.

printing the nodes in linked list in c

here is a program which inserting 2 names 2 paths and 2 duration s into linked list (struct of linked lists) , printing them and swapping between them when the duration of the first node is 8.
but when the program printing the nodes its prints from all of the nodes the name and the path of the last node
please help me
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Frame
{
char *name;
unsigned int duration;
char *path; // may change to FILE*
}*n3;
typedef struct Frame frame_t;
struct Link
{
frame_t *frame;
struct Link *next;
}*n ;
typedef struct Link link_t;
struct Link* insert(struct Link *n3);
void print(struct Link* head, int flag);
void swap(struct Link **head, int value);
#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
int main()
{
struct Link* head = NULL;
int flag = 0;
int num = 0;
char namearray[MAX_NAME_SIZE] = { 0 };
char patharray[MAX_PATH_SIZE] = { 0 };
printf("1\n");
printf("\n");
for (int i = 0; i < 2; i++)
{
printf("Enter a number you want to insert - ");
scanf("%d", &num);
printf("\nEnter the name - ");
scanf("%s", &namearray);
printf("\nEnter the path - ");
scanf("%s", &patharray);
printf("\n");
head = insert(head,num,namearray,patharray);
}
print(head, flag);
swap(&head, 8);
printf("1\n");
system("pause");
return 0;
}
struct Link *insert(struct Link *p, int n, char namearray[MAX_NAME_SIZE], char patharray[MAX_PATH_SIZE]) //insert func
{
struct node *temp;
if (p == NULL) //if the node is empty
{
p = (struct Link *)malloc(sizeof(struct Link)); //gives memory to the node
p->frame = (struct Frame *)malloc(sizeof(struct Frame));
if (p == NULL)
{
printf("Error\n");
}
else
{
printf("The number added to the end of the list\n");
}
p->frame->duration = n; //its runing untill the node item is NULL
p->frame->name = namearray;
p->frame->path = patharray;
p->next = NULL;
}
else
{
p->next = insert(p->next, n , namearray , patharray);/* the while loop replaced by
recursive call */
}
return (p);
}
void print(struct Link* head , int flag)//print func
{
if (head == NULL && flag == 0) //if the node is empty
{
printf("The list is empty\n");
return 1;
}
if (head == NULL && flag != 0) //if the node isnt empty but we are in the NULL (last) item of the node
{
printf("\n");
printf("the nodes of the list printed\n");
return;
}
printf("%d ", head->frame->duration);//prints the currect item
printf("\n");
printf("%s ", head->frame->name);//prints the currect item
printf("\n");
printf("%s ", head->frame->path);//prints the currect item
printf("\n");
print(head->next, ++flag);//calls the func recursevly
return 1;
}
void swap(struct Link **head, int value)
{
while (*head && (*head)->frame->duration != value)
{
head = (*head)->next;
}
if (*head && (*head)->next)
{
struct list *next = (*head)->next->next;
(*head)->next->next = *head;
*head = (*head)->next;
(*head)->next->next = next;
}
}
here is the print :
the print of the program

C: Read Struct into Link List (from File)

I am new to C programming. I have created a student database to enter student details into a linked list (in the form of structure "phbook") and save linked list onto text file. The part I cannot get to work is to read the text file records onto the linked list. The program runs but does not update the linked list when I close the program then select to "LOAD FROM EXTERNAL FILE". Please can someone help me figure what the problem is. I know everything worked until I coded the "readFile" and "insertFull" function. Friends have told me that the global variable "struct phbook *list = NULL;is causing the problem. Please let me know.
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
struct phbook{
int number;
char name[20];
int mark;
struct part *next;
};
struct phbook *list = NULL;
struct phbook *find_student(int number);
void insertFull(struct phbook* list, int number, char Name[10],int mark);
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) SEARCH STUDENT DETAILS: \n");
printf("(3) DISPLAY REPORT OF ALL STUDENTS: \n");
printf("(4) SAVE ALL STUDENT RECORDS TO EXTERNAL FILE: \n");
printf("(5) LOAD ALL STUDENT RECORDS FROM EXTERNAL FILE: \n");
scanf(" %d", &code);
switch (code){
case 1 : insert();
break;
case 2 : search();
break;
break;
case 3 : print();
break;
case 4 :
saveToFile();
break;
case 5 :
readFile();
break;
default: printf("Illegal code\n");
}
printf("\n");
}
}
struct phbook *find_student(int number)
{
struct phbook *p;
for (p = list; p != NULL && number != p->number; p = p->next);//was sorted
if (p != NULL && number == p->number)
return p;
return NULL;
}
void insert(void)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
new_node = (struct phbook*) malloc(sizeof(struct phbook));
if (new_node == NULL){
printf("db full er1.\n");
return;
}
printf("enter student id");
scanf("%d", &new_node->number);
for (cur = list, prev = NULL; cur!= NULL && new_node->number > cur->number; prev = cur, cur = cur->next);
printf("Enter name: ");
scanf("%s", &new_node->name);//readline(new_node->name, NAME_LEN)
printf("Enter MARK: ");
scanf("%d", &new_node->mark);
new_node->next = cur;
if (prev == NULL)
list = new_node;
else
prev->next = new_node;
}
void search(void)
{
int number;
struct phbook *p;
printf("Enter ID: ");
scanf("%d", &number);
p = find_student(number);
if (p != NULL){
printf("Name: %s\n", p->name);
printf("Marks: %d\n", p->mark);
}
else
printf("student not found.\n");
}
void print(void)
{
struct phbook *p;
printf("Student_Number Student_Name Student_Mark\n");
for (p = list; p != NULL; p = p->next)
printf("%7d %-25s %d\n", p->number, p->name, p->mark);
}
void saveToFile()
{
FILE* fp;
fp = fopen ("results.txt","w");
struct phbook* curr = list;//he
while(curr!=NULL)
{
fprintf(fp,"%s\n", list->name);
fprintf(fp,"%d\n",curr->number);
fprintf(fp, "%d\n", curr->mark);
curr = curr->next;
}
fclose(fp);
}
void readFile()
{
FILE* fp;
if (!(fp = fopen ("results.txt", "r")))
printf("File NOT Found");
else{
struct phbook *curr;
struct phbook *prev;
char TempName[10];
int TempNumber;
int TempMark;
int done = 0;
int count = 0;
int success;//dummy
curr = list;//sets it to the head (first nde of ll)
if(list == NULL);
printf("List is null\n");
if(curr == NULL)
printf("List is null\n");
while (curr!=NULL)
{
curr = curr->next;
}
while (done == 0)
{
success = fscanf(fp, "%s", TempName);
if (success == 1)
{
success = fscanf(fp, "%d", &TempNumber);
if (success == 1)
{
success = fscanf(fp, "%d", &TempMark);
if(success == 1)
{
insertFull(list,TempNumber,TempName,TempMark);
}
}
}
else
{
done = 1;
}
}
}
}
void insertFull(struct phbook* list, int number, char Name[10],int mark)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
new_node = (struct phbook*) malloc(sizeof(struct phbook));
if (new_node == NULL){
printf("db full er1.\n");
return;
}
for (cur = list, prev = NULL; cur!= NULL && new_node->number > cur->number; prev = cur, cur = cur->next);
new_node->number = number;
new_node->mark = mark;
strcpy(new_node->name,Name);
new_node->next = cur;
if (prev == NULL)
list = new_node;
else
prev->next = new_node;
}
In the procedure
void insertFull(struct phbook* list, int number, char Name[10],int mark)
you are changing your local copy of list, this has no effect on the global phone book list.
You can remove list from the argument lists, thus changing the global variable:
void insertFull(int number, char Name[10],int mark)
this is not strictly good programming, but it is in line with the rest of your code.

Resources