This is the partial code:
typedef struct {
int dd, mm, yy;
} dateType;
typedef struct {
char username[50], password[50];
int acctype;
dateType date;
} usertype;
typedef struct {
float transactions;
char use[50];
dateType date;
} transactype;
typedef struct node {
usertype employee[2];
usertype admin;
transactype trans[3];
float funds;
int department;
struct node *next;
} nd;
void logon(nd **);
void admin_reg(nd **);
void main(void)
{
int choice;
nd *head, *p;
do {
printf("MENU:\n");
printf("1.Log In\n");
printf("2.Admin/Manager Registration\n");
printf("3.Exit\n");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
logon(&head);
clrscr();
break;
case 2:
admin_reg(&head);
clrscr();
break;
case 3:
exit(1);
break;
default:
printf("Invalid choice.\n");
break;
}
}while(choice!=3);
}
void admin_reg(nd **head)
{
int i;
nd *p;
FILE *fp;
if((fp=fopen("Admin.txt","w"))==NULL)
{
printf("file not found");
exit(1);
}
*head = (nd*)malloc(sizeof(nd));
printf("admin username: ");
scanf("%s",(*head)->admin.username);
printf("admin password: ");
scanf("%s",(*head)->admin.password);
printf("Admin department:1 2 3: ");
scanf("%d",&(*head)->department);
(*head)->admin.acctype=3;
fwrite(*head, sizeof(nd), 1, fp);
p = *head;
for(i = 2; i <= 3; i++)
{
p->next = (nd*)malloc(sizeof(nd));
printf("admin username: ");
scanf("%s",p->next->admin.username);
printf("admin password: ");
scanf("%s",p->next->admin.password);
printf("Admin department:1 2 3: ");
scanf("%d",&p->next->department);
p->next->admin.acctype=3;
fwrite(p->next,sizeof(nd),1,fp);
p = p->next;
}
p->next = NULL;
fclose(fp);
}
void logon(nd **head)
{
nd *p;
char username[50], password[50];
p=*head;
FILE *fp;
if((fp=fopen("Admin.txt","r"))==NULL)
{
printf("file not found");
exit(1);
}
printf("Input username:");
scanf("%s",username);
printf("Input password:");
scanf("%s",password);
while(fread(p, sizeof(nd), 1, fp)==1)
{
if(strcmp(p->admin.username,username)==0 && strcmp(p->admin.password,password)==0)
{
puts(p->admin.username);
puts(p->admin.password);
printf("\nSuccessfully compared!");getch();
}
/* else
{
for(x=0;x<2;x++)
if(strcmp(username,p->employee[x].username)==0 && strcmp(password,p->employee[x].password)==0)
{
y++;
}
} */
p=p->next;
}
fclose(fp);getch();
}
I'm getting an error on the fread part, fwrite is fine. When I try to check if the 2nd or 3rd account could be retrieved the whole program just stops, 1st account seems fine, 2nd and 3rd not.
EDIT: Thanks for those who answered, I finally found the source of my problem, You've all been very helpful. Thanks for the advice. :)
You fread into p but never allocate memory for it, either change p to
nd p;
and pass &p as the first argument to fread, or malloc memory for it:
nd * p = malloc(sizeof(nd));
EDIT: I see that you assign p = *head; in logon and pass head in from main, so the code in logon should work but head isn't allocated in main. So change nd * head to nd head or malloc it.
Related
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
struct Node
{
char firstname[100];
char lastname[100];
char number[100];
char mail[100];
struct Node *next;
}*head;
void insert(char* firstname,char* lastname,char* number,char* mail)
{
struct Node * node=(struct Node *)malloc(sizeof(struct Node));
strcpy(node->firstname, firstname);
strcpy(node->lastname, lastname);
strcpy(node->number, number);
strcpy(node->mail, mail);
node->next=NULL;
if(head==NULL)
{
head=node;
}
else{
node->next=head;
head=node;
}
}
void search(char* firstname)
{
struct Node * temp = head;
while(temp!=NULL){
if(temp->firstname==firstname){
printf("Contact Found");
printf("Firstname:%s\n",temp->firstname);
printf("Lastname:%s\n",temp->lastname);
printf("PhoneNumber:%s\n",temp->number);
printf("Mail Id:%s\n",temp->mail);
return;
}
temp = temp->next;
}
printf("%s is not found in the contact \n",firstname);
}
void update(char* firstname)
{
struct Node * temp=head;
while(temp!=NULL){
if(temp->firstname==firstname){
printf("Contact Found");
printf("Enter the new Phone number for %s\n",temp->firstname);
scanf("%s",temp->number);
printf("Contact Updated Successfully\n");
return;
}
temp=temp->next;
}
printf("%s is not found in the contact \n",firstname);
}
void delete(char* firstname)
{
struct Node * temp1 = head;
struct Node * temp2 = head;
while(temp1!=NULL){
if(temp1->firstname==firstname){
printf("Contact Found for deleting\n");
if(temp1==temp2){
head = head->next;
free(temp1);
}
else{
temp2->next = temp1->next;
free(temp1);
}
printf("Contact deleted Successfully\n");
return;
}
temp2=temp1;
temp1=temp1->next;
}
printf("%s is not found in the contact \n",firstname);
}
void display()
{
struct Node * temp=head;
while(temp!=NULL){
printf("Firstname:%s\n",temp->firstname);
printf("Lastname:%s\n",temp->lastname);
printf("PhoneNumber:%s\n",temp->number);
printf("Mail Id:%s\n",temp->mail);
temp = temp->next;
}
}
int main()
{
head = NULL;
int choice;
char firstname[100];
char lastname[100];
char number[100];
char mail[100];
printf("-------Welcome--------\n ");
printf("1.Insert a Contact\n2.Search a Contact\n3.Delete a Contact\n4.Update a Contact\n5.Display all the Contacts");
do
{
printf("\nEnter Choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter Firstname:");
scanf("%s",firstname);
printf("Enter Lastname:");
scanf("%s",lastname);
printf("Enter PhoneNumber:");
scanf("%s",number);
printf("Enter Mail Id:");
scanf("%s",mail);
insert(firstname,lastname,number,mail);
break;
case 2:
printf("Enter Firstname to Search:");
scanf("%s",firstname);
search(firstname);
break;
case 3:
printf("Enter Firstname to Delete:");
scanf("%s",firstname);
delete(firstname);
break;
case 4:
printf("Enter Firstname to Update:");
scanf("%s",firstname);
update(firstname);
break;
case 5:
display();
break;
}
}while (choice != 0);
}
this c program runs without error but search,delete,update funtion is not working...you can refer the img for more details.
tommorrow i have to submit my mini project..so if anyone knows c program please help me
Enter Choice: 2
Enter Firstname to Search:durai
durai is not found in the contact
Enter Choice: 3
Enter Firstname to Delete:durai
durai is not found in the contact
Enter Choice: 4
Enter Firstname to Update:durai
durai is not found in the contact
these are the errors which i'm getting
For example within the function search you are trying to compare two pointers that point to different extents of memory
if(temp->firstname==firstname){
So the condition evaluates to false even if the pointed strings are equal each other. You have to use the standard string function strcmp
For example
if( strcmp( temp->firstname, firstname ) == 0 ){
Pay attention to that all function parameters that have the type char * should be declared as having the type const char *.
Also it is a bad idea when the functions depend on the global variable head. For example in this case you can not create more than one list in a program.
Hello I am new to c so I had a few issues with my code. My code is supposed to display a menu which displays if you want to add, search, delete, or print all. This works however, my insertion part doesn't. When I select add and start typing the information I want the program crashes?
here is my code
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#pragma warning(disable: 4996)
//#define max 100
typedef enum { diploma, bachelor, master, doctor } education;
struct person { // a node to hold personal details
char name[30];
char email[30];
int phone;
education degree;
struct person* next;
} *head;
void branching(char c);
int insertion();
struct person *search(char *sname);
void deletion(char *sname);
void print_all();
char *x;
//Main Method
int main() { // print a menu for selection
char ch;
do {
printf("Enter your selection\n");
printf("\ti: insert a new entry\n");
printf("\td: delete an entry\n");
printf("\ts: search an entry\n");
printf("\tp: print all entries\n");
printf("\tq: quit \n");
ch = tolower(getchar());
branching(ch);
} while (ch != 113);
return 0;
}
void branching(char c) { // branch to different tasks
switch (c) {
case 'i':
insertion();
break;
case 's':
printf("Enter an item to search");
scanf("%s", x);
search(x);
break;
case 'd':
printf("Enter an item to delete");
scanf("%s", x);
deletion(x);
break;
case 'p':
print_all();
break;
case 'q':
break;
default:
printf("Invalid input\n");
}
}
//insert entry
int insertion(){
struct person *p;
p = (struct person*)malloc(sizeof(struct person));
if (p == 0){
printf("There are no more places to insert.\n"); return -1;
}
printf("Enter name, email, phone, and degree:\n");
scanf("%s", p->name);
scanf("%d", &p->phone);
scanf("%s", p->email);
scanf("%i", p->degree);
p->next = head;
head = p;
return 0;
}
//search method
struct person *search(char *sname){
struct person *p = head, *b = p;
printf("Please enter the name you wish to search:\n");
scanf("%c", sname);
while (p != 0)
if (strcmp(sname, p->name) == 0){
printf("Phone: %d\n", p->phone);
printf("Email: %s\n", p->email);
printf("Degree: %s\n", p->degree);
return b;
}
else{
b = p;
p = p->next;
}
printf("The name does not exist.\n");
return 0;
}
//delete entry
void deletion(char *sname){
struct person *t, *p;
p = head;
t = head;
while (t != NULL){
if (t->name == sname){
if (t == head){//case 1
head = t->next;
free(t);
return;
}
else{
p->next = t->next;
free(t);
return;
}
}
else{
p = t;
t = t->next;
}
}
return;
}
//print
void print_all(){
struct person *p;
p = head;
if (p = NULL){
printf("No entries found.");
}
else{
while (p != NULL){
printf("%s", p->name);
printf("%d", p->phone);
printf("%s", p->email);
printf("%s", p->degree);
p = p->next;
}
printf("\n");
}
}
The variable x needs to point to valid memory. When you make the declaration:
char * x;
The pointer is uninitialized and could point to anywhere in the computer's memory range.
This is why we recommend using std::string and the C++ streams, such as:
std::string x;
cin >> x;
// or
std::getline(cin, x);
Remember, if you dynamically allocate memory for C-Style strings, you have to deallocate the memory.
Also, you need to specify a maximum string length for your input. This is why scanf is an evil function. If you must use scanf, prefer it's other family members, such as fscanf(stdin) or use a format specifier with the maximum size specified.
When comparing the C-style string you will need to use strcmp. When copying the string, use strcpy. If you use std::string, you could use assignment operator and relational operators (more convenient and safe).
I'm doing a program to save a list of contacts in a file whit structs. I've tried a lot of things but when I try go read the file to the program, it doesn't read anything.
This is my program without opening files and saving to files:
#include <stdio.h>
#include <stdlib.h>
struct agenda {
int idContacte;
char name[50];
struct agenda *nextContacte;
};
struct agenda *pAgenda;
struct agenda *pFirst = NULL;
struct agenda *pIndex;
void insert();
void show();
int main()
{
//Menu
int opc;
while(1){
printf("1.Insert Contact.\n");
printf("2.Show Contacts.\n");
printf("3.Exit\n");
scanf("%d", &opc);
switch(opc){
case 1:
insert();
break;
case 2:
show();
break;
case 3:
return 0;
}
}
}
void insert(){
pAgenda = (struct agenda *)malloc(sizeof(struct agenda));
printf("Insert ID: ");
scanf("%d", &pAgenda->idContacte);
printf("Insert the name: ");
scanf("%s", pAgenda->name);
printf("\n");
if (pFirst==NULL || pAgenda->idContacte < pFirst->idContacte)
{
pAgenda->nextContacte=pFirst;
pFirst=pAgenda;
}
else if (pAgenda->idContacte > pFirst->idContacte){
pIndex=pFirst;
while(pIndex->nextContacte && pIndex->nextContacte->idContacte < pAgenda->idContacte)
{
pIndex = pIndex->nextContacte;
}
pAgenda->nextContacte = pIndex->nextContacte;
pIndex->nextContacte = pAgenda;
}
}
void show(){
pIndex = pFirst;
while(pIndex && pIndex->idContacte <= 100) {
printf("\nID: %d", pIndex->idContacte);
printf("\nNAME: %s", pIndex->name);
printf("\n\n");
pIndex = pIndex->nextContacte;
}
}
Can you help me how can I get contact at start of the program from a file, and then when insert a contact, rewrite the file and insert all the contacts again in the file?
When you end your program you should do the following
int save_list(struct agenda *head) {
FILE *save = fopen("file.name", "wb");
if(!save) return -1;
while(head) {
fwrite(head, sizeof *head - sizeof head, 1, save);
head = head->nextContacte;
}
fclose(save);
/* Somebody would free list memory after this function execution */
return 0;
}
At the start of your program you should do the following
struct agenda *restore_list() {
FILE *restore= fopen("file.name", "rb");
struct agenda *head = NULL;
struct agenda *cur = head;
struct agenda temp;
if(!restore) return head;
while( fwrite(&temp, sizeof temp - sizeof head, 1, save) == 1) {
struct agenda *node = malloc( sizeof(struct agenda) );
if(NULL == node) {
/* Handle out of memory error here, free list */
return NULL;
}
*node = temp;
node->nextContacte = NULL;
if(head) {
cur->nextContacte = node;
cur = node;
} else {
/* First node */
head = cur = node;
}
}
fclose(restore);
return head;
}
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct student{
char firstname[20];
char lastname[20];
double grade;
char zipcode[10];
struct student *next;
};
void display(struct student *first)
{
while (first != NULL)
{
printf("\nFirst name: %s", first->firstname);
printf("\tLast name: %s", first->lastname);
printf("\tGrade: %.2f", first->grade);
printf("\t ZipCode: %s", first->zipcode);
first = first->next;
}
}
/*void add_Record(struct student *first)
{
char r[20];
struct student *t;
t = first;
while (t != NULL)
{
if (t == NULL)
{
first = (struct student*)malloc(sizeof(struct student));
printf("\nEnter the first name of the student:");
scanf("%s", first->firstname);
printf("\nEnter the last name of the student:");
scanf("%s", first->lastname);
printf("\nEnter the score of the student:");
scanf("%lf", &first->grade);
printf("\nEnter the zipcode of the student:");
scanf("%s", first->zipcode);
}
}
}
void del()
{
struct student *back, *t, *k;
char r[10];
int flag = 0;
printf("\nEnter the last name of student you want to delete:");
scanf("%s", r);
if (strcmpi(r, first->lastname) == 0)
{
first = first->next;
flag = 1;
}
else
{
back = first;
k = first->next;
while (k != NULL)
{
if (strcmpi(r, k->lastname) == 0)
{
back->next = k->next;
flag = 1;
break;
}
}
}
if (flag == 0)
printf("\nThe element not found!!!");
}
*/
void search(struct student *first)
{
char r[10];
int flag = 0;
printf("\nEnter the zipcode you want to search:");
scanf("%s", r);
struct student *t;
t = first;
while (t != NULL)
{
if (strcmp(r, t->zipcode) == 0)
{
printf("\nFirst name: %s", t->firstname);
printf("\tLast name: %s", t->lastname);
printf("\tGrade: %.2f", t->grade);
printf("\t ZipCode: %s", t->zipcode);
flag = 1;
break;
}t = t->next;
}
if (flag == 0)
printf("\nThe zipcode not in database!!");
}
void sort(struct student *first)
{
struct student *temp;
temp = NULL;
while (first != NULL)
{
if (first-> grade > first->next->grade)
{
strcpy(temp->firstname, first->firstname);
strcpy(temp->lastname, first->lastname);
temp->grade = first->grade;
strcpy(temp->zipcode, first->zipcode);
strcpy(first->firstname, first->next->firstname);
strcpy(first->lastname, first->next->lastname);
first->grade = first->next->grade;
strcpy(first->zipcode, first->next->zipcode);
strcpy(first->next->firstname, temp->firstname);
strcpy(first->next->lastname, temp->lastname);
first->next->grade = temp->grade;
strcpy(first->next->zipcode, temp->zipcode);
break;
}
}
printf("\nThe sorted record by score are: \n");
display(first);
}
int main(void)
{
struct student *first = NULL, *last = NULL;
struct student *temp;
int n;
printf("\nEnter the number of student:");
scanf("%d", &n);
int i;
for (i = 0; i < n; i++)
{
temp = (struct student*)malloc(sizeof(struct student));
printf("\nEnter the first name of the student:");
scanf("%s", temp->firstname);
printf("\nEnter the last name of the student:");
scanf("%s", temp->lastname);
printf("\nEnter the grade of the student:");
scanf("%lf", &temp->grade);
printf("\nEnter the zipcode of the student:");
scanf("%s", temp->zipcode);
temp->next = first;
first = temp;
}
int o;
o = 1;
while (o != 0)
{
printf("\nMENU\n");
printf("\nEnter 1 for displaying database.");
printf("\nEnter 2 for inserting an record.");
printf("\nEnter 3 for deleting a record by lastname.");
printf("\nEnter 4 for searching a record by zipcode.");
printf("\nEnter 5 for sorting record by score.");
printf("\nEnter 0 for exit!");
printf("\nEnter the choice:");
scanf("%d", &o);
switch (o)
{
case 1:display(first); break;
/*case 2:insertafter(*first); break;
case 3:del(); break;*/
case 4:search(first); break;
case 5: sort(first); break;
case 0:exit(0); break;
default:printf("\nYou have entered a wrong choice!!!");
}
}
}
The problem is that how do i sort the scores by score. My code seems right but doesn't work. I made a temp structure and tried to swap values but it doesn't work. Am i doing the loop wrong? Or all my code is wrong?
Here are two answers to the problem
First one sorts the nodes in the node linked list by bubble sorting them, rearranging the linked list
Second one walks the linked list, copies a pointer to each one into an array and then sorts the array by using the struct grade members, the linked list remains unchanged
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define SWAP(T,x,y) {T *p = &(x); T *q = &(y); T z = *p; *p = *q; *q = z;}
struct student{
char firstname[20];
char lastname[20];
double grade;
char zipcode[10];
struct student *next;
};
struct student *head=NULL;
void add(char *f, char *s, double score) {
struct student *a;
a=(struct student*)malloc(sizeof(struct student));
strcpy(a->firstname,f);
strcpy(a->lastname,s);
a->grade = score;
a->next = head;
head = a;
}
void printout(char *label) {
struct student *node;
printf("%s\n",label);
for(node=head; node !=NULL; node=node->next) {
printf("%s %s %f\n", node->firstname, node->lastname, node->grade);
}
}
int main(int argc, char ** argv){
int mark=8;
struct student *walk, *prev;
add("Bob","Smith",10);
add("Eric","Von Däniken",90);
add("Morris","Minor",91);
add("Master","Bates",9);
add("Zoe","Bodkin",20);
add("Mary","Pippin",30);
/* bubble sort */
printout("before");
prev=head;
while(mark) {
mark=0;
for(walk=head;
walk != NULL;
walk=walk->next) {
if (walk->next && walk->grade > walk->next->grade) {
/* printf("swapping %s %s\n", walk->firstname, walk->next->firstname); */
mark=1;
if (walk == head) {
struct student *v2=walk->next;
struct student *v3=walk->next->next;
SWAP(struct student *, v3->next, v2->next);
SWAP(struct student *, head, v3->next);
walk = v3;
} else {
struct student *v1=prev;
struct student *v2=walk;
struct student *v3=walk->next;
SWAP(struct student *, v3->next, v2->next);
SWAP(struct student *, v1->next, v3->next);
walk = v3;
}
}
prev=walk;
}
}
printout("after");
return 0;
}
second version, uses qsort, retains linked list order
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
struct student{
char firstname[20];
char lastname[20];
double grade;
char zipcode[10];
struct student *next;
};
struct student *head=NULL;
size_t nodecount=0;
void add(char *f, char *s, double score) {
struct student *a;
a=(struct student*)malloc(sizeof(struct student));
strcpy(a->firstname,f);
strcpy(a->lastname,s);
a->grade = score;
a->next = head;
head = a;
nodecount++;
}
static int cmpgrade(const void *p1, const void *p2) {
struct student *g1, *g2;
g1=*(struct student **)p1;
g2=*(struct student **)p2;
return g1->grade > g2->grade;
}
int main(int argc, char ** argv){
int i;
struct student *walk,**sa, **sap;
add("Bob","Smith",10);
add("Eric","Von Däniken",90);
add("Morris","Minor",91);
add("Master","Bates",9);
add("Zoe","Bodkin",20);
add("Mary","Pippin",30);
/*copy into array of pointers*/
sa=calloc(sizeof (struct student*), nodecount);
sap=sa;
for(walk=head; walk != NULL; walk=walk->next) {
*sap = walk;
sap++;
}
printf("before\n");
for (i=0; i< nodecount; i++) {
printf("%s %s %f\n", sa[i]->firstname, sa[i]->lastname, sa[i]->grade);
}
/* qsort */
qsort(sa, nodecount, sizeof (struct student *), cmpgrade);
printf("after\n");
for (i=0; i< nodecount; i++) {
printf("%s %s %f\n", sa[i]->firstname, sa[i]->lastname, sa[i]->grade);
}
return 0;
}
I am coding for a simple linked list , but facing a little problem. The program is like it is accepting name, age and DOB through user, and memory for it is dynamically allocated. After taking data from the user, it is searching a name, asked by user, if the name exists, it should print all the details related to it.
Here is my code-
//function declarations
struct node *initnode(char *, char *, char *);
void add(struct node *);
struct node *printnode(struct node *);
struct node *searchname(struct node *, char *);
struct node {
char name[25];
char age[10];
char dob[10];
struct node *next;
};
struct node *head = (struct node *) NULL;
struct node *initnode(char *name, char *age, char *dob1)
{
struct node *ptr;
ptr = (struct node *) malloc(sizeof(struct node));
if (ptr == NULL)
return (struct node *) NULL;
else {
strcpy(ptr->name, name);
strcpy(ptr->age, age);
strcpy(ptr->dob, dob1);
ptr->next = NULL;
return ptr;
}
}
struct node *printnode(struct node *ptr)
{
printf("Name -> %s\n", ptr->name);
printf("age -> %s \n", ptr->age);
printf("dob ->%s\n", ptr->dob);
return ptr;
}
void add(struct node *newp)
{
struct node *temp = (struct node *) malloc(sizeof(struct node));
if (head == NULL)
head = newp;
else {
for (temp = head; temp->next != NULL; temp = temp->next);
temp->next = newp;
temp = newp;
}
free(temp);
}
struct node *searchname(struct node *ptr, char *name1)
{
if (strcmp(name1, ptr->name) == 0) {
printf("\n name found \n");
printf("\n details are -\n");
printnode(ptr);
return ptr;
} else {
printf("\n name not found in the database \n");
}
}
int main()
{
char name[25];
char name1[25];
char rep;
char age[10];
char dob[10];
int i;
int flag = 1;
struct node *ptr;
do {
fflush(stdin);
while (flag != 0) {
printf("Enter name -- ");
gets(name);
for (i = 0; name[i] != '\0'; i++)
if (isdigit(name[i])) {
printf("Error in user input, name should be in alphabets\n");
flag = 1;
break;
}
else
flag = 0;
}
flag = 1;
while (flag != 0) {
printf("Enter age -- ");
scanf("%s", &age);
fflush(stdin);
for (i = 0; age[i] != '\0'; i++)
if (isalpha(age[i])) {
printf("Error in user input, age should be in numbers\n");
flag = 1;
break;
} else {
flag = 0;
}
}
flag = 1;
while (flag != 0) {
printf("Enter dob in DD/MM/YY format-- ");
scanf("%s", &dob);
fflush(stdin);
for (i = 0; dob[i] != '\0'; i++) {
if (isalpha(dob[i])) {
printf("Error in user input, dob should be in numbers\n");
flag = 1;
break;
} else
flag = 0;
}
}
flag = 1;
ptr = initnode(name, age, dob);
add(ptr);
printf("\n Do you want to continue?<Y/N>:\n ");
scanf("%s", &rep);
//rep = getchar();
}
while (rep == 'Y' || rep == 'y');
printf("\n do u want to search for a name in the database? <Y/N>:\n");
scanf("%s", &rep);
if (rep == 'Y' || rep == 'y') {
printf("Enter name you want to search-- ");
scanf("%s", &name1);
ptr = searchname(head, name1);
} else {
printf("\n goodbye \n");
}
do {
printf("\n do u want to search again? <Y/N>:\n");
scanf("%s", &rep);
if (rep == 'Y' || rep == 'y') {
printf("Enter name you want to search-- ");
scanf("%s", &name1);
ptr = searchname(head, name1);
} else {
printf("\n goodbye \n");
}
}
while (rep == 'Y' || rep == 'y');
return 0;
}
The issue is that it is searching for the first entry only and not others, can anyone help me to sort out this? I am compiling through "gcc".
At a first glance, your search function is only comparing one element, the head of the list.
After comparing one element you must go to the next element. This can either be done recursively or with a while:
Recursive use:
struct node *searchname(struct node *ptr, char *name1)
{
if (ptr==NULL) //Reached end of the list
{
printf("\n name not found in the database \n");
return NULL;
}
if (strcmp(name1, ptr->name) == 0) { //found the element
printf("\n name found \n");
printf("\n details are -\n");
printnode(ptr);
return ptr;
} else { //search next element
return searchname(ptr->next,name1); //this will call your function again for the next element on the list
}
}
While use:
struct node *searchname(struct node *ptr, char *name1)
{
struct node *aux; // usually i use an auxiliary pointer in order to avoid unwanted overwrite at my pointer.
aux = ptr;
while (aux!=NULL)
{
if (strcmp(name1, aux->name) == 0) { //found the element
printf("\n name found \n");
printf("\n details are -\n");
printnode(aux);
return aux;
}
else { //move pointer to next element
aux=aux->next;
}
}
//if it reaches this point, the element was not found
printf("\n name not found in the database \n");
return NULL;
}
Check your add function, it is wrong. Step mentally through it, and see what happens
to your pointer, and to the memory it points to.
What are the malloc and free used for in the add function?