Difference between char, char* inside Linked Lists - c

I created a linked list that hold int and char type data. A function adds the data to the list and the other prints it out. When i only print the int type i get no problems but when i try to also print the char type the program crashes.
So it has to do the way i'm defining the char* in the printing function print_list().
To be more specific my problem is here in print_list() :
printf("\n [%s] \n", ptr -> name);
printf("\n [%s] \n", ptr -> lastn);
So my actual code is (getting 0 errors and 0 warnings but the program crashes):
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Creating structure for node
struct test_struct
{
int val; // val is member id number
char name;
char lastn;
int age;
struct test_struct *next;
};
// declaring global head and curr pointers
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
// creating a list
struct test_struct* create_list(int val, char* name, char* lastn, int age)
{
printf("\n creating list with head node as [%d] [%s] [%s] [%d] \n", val, name, lastn, age);
struct test_struct *ptr = malloc(sizeof(struct test_struct)); // creating list
if(NULL == ptr) {
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->name = *name;
ptr->lastn = *lastn;
ptr->age = age;
ptr->next = NULL;
head = curr = ptr;
return ptr;
}
// add member to list
struct test_struct* add_to_list(int val, char *name, char *lastn, int age, bool add_to_end)
{
if(NULL == head) {
return (create_list(val, name, lastn, age));
}
if(add_to_end) {
printf("\n Adding node to end of list with data [%d] [%s] [%s] [%d] \n", val, name, lastn, age);
} else {
printf("\n Adding node to beginning of list with data [%d] [%s] [%s] [%d] \n", val, name, lastn, age);
}
struct test_struct *ptr = malloc(sizeof(struct test_struct));
if(NULL == ptr) {
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->name = *name;
ptr->lastn = *lastn;
ptr->age = age;
ptr->next = NULL;
if (add_to_end) {
curr-> next = ptr;
curr = ptr;
} else {
ptr -> next = head;
head = ptr;
}
return ptr;
}
//printing the list
void print_list(void)
{
struct test_struct *ptr = head;
printf("\n -----Printing list Start----- \n");
while(ptr != NULL) {
printf("\n [%d] \n", ptr -> val);
printf("\n [%s] \n", ptr -> name);
printf("\n [%s] \n", ptr -> lastn);
printf("\n [%d] \n", ptr -> age);
ptr = ptr->next;
}
printf("\n -----Printing list end---- \n");
return;
}
// main function
int main(void)
{
struct test_struct *ptr = NULL;
// for adding member to list
add_to_list(123, "william", "shakespeare", 30, true);
add_to_list(124, "william", "gibson", 35, true);
add_to_list(125, "chuck", "palahniuk", 40, true);
add_to_list(126, "mario", "puzio", 50, true);
add_to_list(127, "umberto", "eco", 60, true);
add_to_list(128, "ezra", "pound", 125, true);
print_list();
return 0;
}

You have declared name and lastn as single characters
struct test_struct
{
int val; // val is member id number
char name;
char lastn;
int age;
struct test_struct *next;
};
you need to declare them either as fixed size arrays or pointers which point to allocated space to hold the strings. A string is a series of characters terminated by a \0.
struct test_struct
{
int val; // val is member id number
char name[MAXLEN];
char lastn[MAXLEN];
int age;
struct test_struct *next;
};
then copy arguments to the function to the fields in the struct
e.g.
strcpy(ptr->name,name);
strcpy(ptr->lastn,lastn);

printf("\n [%s] \n", ptr -> name);
printf("\n [%s] \n", ptr -> lastn);
%s expects char * not char as both name and lastn are char variables.
And to store name and last name of a person you should prefer char array as single char variable can't store it . Therefore , declare them as char arrays .
Example -
struct test_struct
{
int val; // val is member id number
char name[20]; // or any desired length to store a name
char lastn[20]; // similar as for name
int age;
struct test_struct *next;
};
And then to copy data in it use strncpy-
ptr->name = *name; // strncpy(ptr->name,name,strlen(name));
ptr->lastn = *lastn; // strncpy(ptr->lastn,lastn,strlen(lastn));

Related

Build a linked list in c

I am attempting to create a linked list from a file using structs, when I run the print_list it is not printing the name or threat level, but it is printing the ID. I have little experience with structs but I believe I am not understanding if the pointers are being used correctly here.
void insert(struct poi_t_struct **head_ref, char *name, long int id, int threat_level) {
// printf("Name from insert %s \n", name); // debug
struct poi_t_struct newNode = { name, id, threat_level, NULL };
struct poi_t_struct *ptr_newNode = &newNode;
struct poi_t_struct *temp = *head_ref;
}
void buildLList(char *filename) {
FILE *poiProfiles;
// char line[MAX_LINE_LENGTH];
// have 3 char arrays. One for each name, id, threat level
char idLine[MAX_LINE_LENGTH];
char nameLine[MAX_LINE_LENGTH];
char threat_levelLine[MAX_LINE_LENGTH];
while (fgets(idLine, MAX_LINE_LENGTH, poiProfiles)) {
long int id;
id = atoi(idLine);
fgets(nameLine, MAX_LINE_LENGTH, poiProfiles);
char* name;
name = nameLine;
fgets(threat_levelLine, MAX_LINE_LENGTH, poiProfiles);
int threat_level;
threat_level = atoi(threat_levelLine);
insert(&head, name, id, threat_level);
}
void print_list(struct poi_t_struct *p) {
struct poi_t_struct *temp = p;
while (temp != NULL) {
print_record(temp);
temp = temp->next;
}
}
There are multiple problems in your code:
you do not open nor close the file for poiProfiles
there is a missing } at the end of the buildLList() function.
the insert function must allocate memory for the new node, inserting a local struct object is incorrect as this object becomes invalid as soon as the function returns. You attempt to insert the new node at the beginning of the list, but you neither set the next member of the struct, not set *head_ref to point to the new node.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct poi_t_struct {
char *name;
long int id;
int threat_level;
struct poi_t_struct *next;
} *head;
int insert(struct poi_t_struct **head_ref, const char *name, long int id, int threat_level) {
// printf("Name from insert %s \n", name); // debug
struct poi_t_struct *ptr_newNode = malloc(sizeof *ptr_newNode);
if (ptr_newNode == NULL)
return -1;
ptr_newNode->name = strdup(name);
ptr_newNode->id = id;
ptr_newNode->threat_level = threat_level;
ptr_newNode->next = *head_ref;
*head_ref = ptr_newNode;
return 0;
}
int buildLList(const char *filename) {
// have 3 char arrays. One for each name, id, threat level
char idLine[MAX_LINE_LENGTH];
char nameLine[MAX_LINE_LENGTH];
char threat_levelLine[MAX_LINE_LENGTH];
FILE *poiProfiles;
int count = 0;
poiProfiles = fopen(filename, "r");
if (poiProfiles == NULL) {
fprintf(stderr, "cannot open %s: %s\n", filename, strerror(errno));
return -1;
}
while (fgets(idLine, MAX_LINE_LENGTH, poiProfiles)
&& fgets(nameLine, MAX_LINE_LENGTH, poiProfiles)
&& fgets(threat_levelLine, MAX_LINE_LENGTH, poiProfiles)) {
long int id = atoi(idLine);
char *name = nameLine;
int threat_level = atoi(threat_levelLine);
if (!insert(&head, name, id, threat_level))
count++;
}
fclose(poiProfiles);
return count;
}
void print_list(const struct poi_t_struct *p) {
const struct poi_t_struct *temp = p;
while (temp != NULL) {
print_record(temp);
temp = temp->next;
}
}

Linked List - Stack Sorting in C

My code is following:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<math.h>
struct stack {
int data;
struct stack* next;
};
struct Student
{
unsigned long int rollnumber;
char name[100];
struct Student *next;
}* head;
// Utility function to initialize stack
void initStack(struct stack** s) { *s = NULL; }
// Utility function to check if stack is empty
int isEmpty(struct stack* s)
{
if (s == NULL)
return 1;
return 0;
}
// Utility function to push an item to stack
void push(struct stack** s, int x, unsigned long int rollnumber, char *name)
{
struct stack* p = (struct stack*)malloc(sizeof(*p));
if (p == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
return;
}
p->data = x;
p->next = *s;
*s = p;
}
// Utility function to remove an item from stack
int pop(struct stack** s)
{
int x;
struct stack* temp;
x = (*s)->data;
temp = *s;
(*s) = (*s)->next;
free(temp);
return x;
}
// Function to find top item
int top(struct stack* s) { return (s->data); }
// Recursive function to insert an item x in sorted way
void sortedInsert(struct stack** s, int x, unsigned long int rollnumber, char *name)
{
// Base case: Either stack is empty or newly inserted
// item is less than top (more than all existing)
if (isEmpty(*s) || x < top(*s)) {
push(s, x, rollnumber, name);
return;
}
else{
// If top is less, remove the top item and recur
int temp = pop(s);
sortedInsert(s, x, rollnumber, name);
// Put back the top item removed earlier
push(s, temp, rollnumber, name);}
}
// Function to sort stack
void sortStack(struct stack** s)
{
// If stack is not empty
char *name;
unsigned long int rollnumber;
if (!isEmpty(*s)) {
// Remove the top item
int x = pop(s);
// Sort remaining stack
sortStack(s);
// Push the top item back in sorted stack
sortedInsert(s, x, rollnumber, name);
}
}
// Utility function to print contents of stack
void printStack(struct stack* s, unsigned long int rollnumber, char* name)
{
struct Student* student = (struct Student *) malloc(sizeof(struct Student));
struct Student* temp = head;
while (s && temp!=NULL) {
printf("%lu %s\n", temp->rollnumber, temp->name);
s = s->next;
temp = temp->next;
}
printf("\n");
}
void insert(unsigned long int rollnumber, char* name)
{
struct Student * student = (struct Student *) malloc(sizeof(struct Student));
student->rollnumber = rollnumber;
strcpy(student->name, name);
student->next = NULL;
if(head==NULL){
// if head is NULL
// set student as the new head
head = student;
}
else{
// if list is not empty
// insert student in beginning of head
student->next = head;
head = student;
}
}
void Delete(unsigned long int rollnumber)
{
struct Student * temp1 = head;
struct Student * temp2 = head;
while(temp1!=NULL){
if(temp1->rollnumber==rollnumber){
printf("Record with roll number %lu Found\n", rollnumber);
if(temp1==temp2){
// this condition will run if
// the record that we need to delete is the first node
// of the linked list
head = head->next;
free(temp1);
}
else{
// temp1 is the node we need to delete
// temp2 is the node previous to temp1
temp2->next = temp1->next;
free(temp1);
}
printf("Record successfully deleted\n");
return;
}
temp2 = temp1;
temp1 = temp1->next;
}
printf("Student with roll number %lu is not found\n", rollnumber);
}
void display()
{
struct Student * temp = head;
while(temp!=NULL){
printf("Roll Number: %lu\n", temp->rollnumber);
printf("Name: %s\n", temp->name);
temp = temp->next;
}
}
int main(void)
{
head = NULL;
int choice;
int fc_,id_,year_, fc_year;
char name[100];
struct student* s;
unsigned long int rollnumber;
struct stack* faculty;
struct stack* year;
struct stack* id;
initStack(&faculty);
initStack(&year);
initStack(&id);
printf("1 - Enter school number\n2 - Display school numbers by ID\n3 - Display school numbers sorted by year\n4 - Display school numbers sorted by the faculty codes\n5 - Delete a record by school number\n6 - Exit");
do
{
printf("\nEnter Choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter roll number: ");
scanf("%lu", &rollnumber);
fc_ = rollnumber/pow(10, 6);
id_ = rollnumber%(10*10*10*10);
fc_year = rollnumber/pow(10,4);
year_ = fc_year%(100);
printf("Enter name: ");
scanf("%s", name);
insert(rollnumber, name);
push(&faculty, fc_, rollnumber, name);
push(&year, year_, rollnumber, name);
push(&id, id_, rollnumber, name);
break;
case 2:
printf("Sorted by ID: \n");
sortStack(&id);
printStack(id, rollnumber, name);
break;
case 3:
printf("Sorted by year: \n");
sortStack(&year);
printStack(year, rollnumber, name);
break;
case 4:
printf("Sorted by faculty code: \n");
sortStack(&faculty);
printStack(faculty, rollnumber, name);
break;
case 5:
printf("Enter roll number to delete: ");
scanf("%lu", &rollnumber);
Delete(rollnumber);
break;
case 6:
break;
}
} while (choice != 6);
}
When, for example, the choice is 2, I want to display the student name and whole rollnumber in ascending order. But when I run it that is what I get (C, B, A are the names given by me):
Enter Choice: 2
705102020 C
705102010 B
705102005 A
I am sure that I sorted it correctly, but probably my printStack function is not working properly. How can I reverse this?
It would be better to define a stack struct independantly of the rest of your code:
struct stack {
void *data;
struct stack *next;
};
void stack_init(struct stack **ss)
{
*ss = NULL;
}
bool stack_push(struct stack **ss, void *data)
{
struct stack *node = malloc(sizeof *node);
if (!node) return false;
node->data = data; // Copy address, not data
node->next = *ss;
*ss = node;
return true;
}
bool stack_pop(struct stack **ss, void **data)
{
if (!*ss) return false;
struct stack *rm = *ss;
*ss = (*ss)->next;
if (data) *data = rm->data; // If nothing is provided (i.e. NULL), data will leak if it was allocated dynamically.
free(rm);
return true;
}
bool stack_top(const struct stack *ss, void **data)
{
if (!ss) return false;
*data = ss->data;
return true;
}
void stack_print(const struct stack *ss, void print(const struct stack*))
{
for (const struct stack *sp = ss; sp; sp = sp->next)
print(sp);
}
You can implement your stack sorting function like that:
struct stack *stack_find_min(struct stack *ss, int (*cmp)(const void*, const void*))
{
struct stack *min = ss;
for (struct stack *sp = ss; sp; sp = sp->next)
if (cmp(sp->data, min->data) < 0)
min = sp;
return min;
}
void stack_sort(struct stack *ss, int (*cmp)(const void*, const void*))
{
if (!ss) return;
for (struct stack *sp = ss; sp; sp = sp->next) {
struct stack *min = stack_find_min(sp, cmp);
swap(&sp->data, &min->data);
}
}
swap() swaps two pointers:
void swap(void **p1, void **p2)
{
void *tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
After that, define your student data structure:
struct student {
unsigned long rollnumber;
char name[100];
struct student *next;
};
struct student *student_insert(struct student **head, unsigned long rollnumber, const char *name)
{
struct student *st = malloc(sizeof(*st));
if (!st) return NULL;
st->rollnumber = rollnumber;
strncpy(st->name, name, 99);
st->next = *head;
*head = st;
return st;
}
void student_print(const struct stack *ss)
{
struct student *st = ss->data;
printf("%ld\t%s\n", st->rollnumber, st->name);
}
int student_compare_id(const void *s1, const void *s2)
{
// MUST cast void* into (struct student*) first.
const struct student *student1 = s1;
const struct student *student2 = s2;
unsigned long rollnumber1 = student1->rollnumber;
unsigned long rollnumber2 = student2->rollnumber;
unsigned long id1 = rollnumber1 % 10000;
unsigned long id2 = rollnumber2 % 10000;
return id1 == id2 ? 0 : (id1 < id2 ? -1 : 1);
}
If you want to test the above:
int main(void)
{
struct stack *ss;
stack_init(&ss);
struct student *st = NULL;
student_insert(&st, 100181234, "James");
student_insert(&st, 200195678, "John");
student_insert(&st, 300200324, "Goku");
student_insert(&st, 400214321, "Taylor");
for (struct student *p = st; p; p = p->next)
stack_push(&ss, p);
puts("Unsorted stack:");
stack_print(ss, student_print);
stack_sort(ss, student_compare_id);
puts("\nSorted by ID:");
stack_print(ss, student_print);
// Don't forget to free the memory allocated for students
// and pop all nodes of the stack (ommited here).
}
Output:
Unsorted stack:
100181234 James
200195678 John
300200324 Goku
400214321 Taylor
Sorted by ID:
300200324 Goku
100181234 James
400214321 Taylor
200195678 John
Few more things:
Don't use scanf() to read user input. fgets() is safer.
You can replace pow(10, 4) directly by 10000. Why wasting CPU cycles to calculate constants?
In your insert() function, there is no need to test for *head == NULL. The code in the else statement handles this case.
EDIT: In student_compare_id(), the const void* pointers MUST BE CASTED to const struct student* first before dereferencing. The previous version seemed to work because the rollnumber happened to be the first field in the struct. That was an undefined behavior in all its glory. Fixed that now.
Here is the previous version that NO ONE SHOULD USE:
int student_compare_id(const void *s1, const void *s2)
{
unsigned long rollnumber1 = *(unsigned long*)s1; // WRONG!
unsigned long rollnumber2 = *(unsigned long*)s2; // WRONG!
unsigned long id1 = rollnumber1 % 10000;
unsigned long id2 = rollnumber2 % 10000;
return id1 == id2 ? 0 : (id1 < id2 ? -1 : 1);
}
The primary problem is that there is no connection between your stack(s) and your student list, but the code assumes that there is. You can reorder the stacks however you like, but that does not reorder the list. When you print, the students simply come out in the reverse of their insertion order (because you insert at the front of the list, and then traverse the list from front to back).
You have two main alternatives:
combine the list and all the stacks into one linked list. You can use this both list-style and stack-style if you like. OR
Give the stack nodes pointers to the corresponding list elements, and traverse those when you print a stack to get the students in the order implied by the stack.

Insert from file to chained list C

iam trying to read the data i saved in the file record.txt with the function and then read from file and insert the data into the linked list again but iam getting an infinite loop when I display the data from the list with i cant find the problem!
idk if the problem in the save function or the getfile function or the dispal i cant find any hint on my problem
Code:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<windows.h>
#include <unistd.h>
int import = 0 ;
struct Repertoire
{
char phone[10];
char name[100];
char lastname[100];
char adresse[100];
char date[100];
char email[100];
struct Repertoire *next;
}* head;
void insert(char* phone, char* name, char* lastname, char* adresse, char* email, char* date)
{
struct Repertoire * rep = (struct Repertoire *) malloc(sizeof(struct Repertoire));
strcpy(rep->phone, phone);
strcpy(rep->name, name);
strcpy(rep->lastname, lastname);
strcpy(rep->adresse, adresse);
strcpy(rep->email, email);
strcpy(rep->date, date);
rep->next = NULL;
if(head==NULL){
// if head is NULL
// set student as the new head
head = rep;
}
else{
// if list is not empty
// insert student in beginning of head
rep->next = head;
head = rep;
}
}
void display()
{
struct Repertoire * temp = head;
while(temp!=NULL){
printf("Phone Number: %s\n", temp->phone);
printf("Name: %s\n", temp->name);
printf("Lastname: %s\n", temp->lastname);
printf("Adresse: %s\n", temp->adresse);
printf("Date of birth: %s\n", temp->date);
printf("email: %s\n", temp->email);
temp = temp->next;
}
}
void insertFile(){
struct Repertoire * temp = head;
FILE *ptr;
ptr=fopen("record.txt","a+");
while(temp!=NULL){
fprintf(ptr,"%s %s %s %s %s %s\n",temp->phone,temp->name,temp->lastname,temp->adresse,temp->date,temp->email);
temp = temp->next;
}
fclose(ptr);
}
void SaveFile(){
struct Repertoire * temp = head;
FILE *ptr;
ptr=fopen("new.txt","w");
while(temp!=NULL){
fprintf(ptr,"%s %s %s %s %s %s\n",temp->phone,temp->name,temp->lastname,temp->adresse,temp->date,temp->email);
temp = temp->next;
}
fclose(ptr);
remove("record.txt");
rename("new.txt","record.txt");
}
void GetFile(){
char phone[10];
char name[100];
char lastname[100];
char adresse[100];
char date[100];
char email[100];
FILE *ptr;
ptr=fopen("record.txt","r");
struct Repertoire * rep = (struct Repertoire *) malloc(sizeof(struct Repertoire));
while(fscanf(ptr,"%s %s %s %s %s %s\n",phone,name,lastname,adresse,date,email)!=EOF){
strcpy(rep->phone, phone);
strcpy(rep->name, name);
strcpy(rep->lastname, lastname);
strcpy(rep->adresse, adresse);
strcpy(rep->email, email);
strcpy(rep->date, date);
rep->next = NULL;
if(head==NULL){
// if head is NULL
// set student as the new head
head = rep;
}
else{
// if list is not empty
// insert student in beginning of head
rep->next = head;
head = rep;
}
}
free(rep);
printf("Data Ipmorted Successfully !!");
import = 1 ;
fclose(ptr);
}
I found the answer :
void GetFile(){
FILE *ptr;
ptr=fopen("record.txt","r");
struct Repertoire * rep = (struct Repertoire *) malloc(sizeof(struct Repertoire));
while(!feof(ptr)){
fscanf(ptr,"%s %s %s %s %s %s\n",rep->phone,rep->name,rep->lastname,rep->adresse,rep->date,rep->email);
insert(rep->phone,rep->name,rep->lastname,rep->adresse,rep->date,rep->email);
}
printf("Data Ipmorted Successfully !!\n");
import = 1 ;
fclose(ptr);
}

Printing the items in a structure

I want to print the elements from a structure in c, but the send and third print statements give me the warning: format specifies type 'char *' but the argument has type 'char'. I know it has to do with the pointer, but I don't know what I'm doing wrong. I have also modified it to show the 2 structures I am using.
struct student_record{
int student_id;
int student_age;
char first_name;
char last_name; };
struct student_record_node{
struct student_record* record;
struct student_record_node* next;
struct student_record_node* prev; };
void printNode(struct student_record_node *node){
printf("Struct student_record_node: \n");
printf(" student first_name: %s\n", node->record->first_name);
printf(" student last_name: %s\n", node->record->last_name);
printf(" student id: %d\n", node->record->student_id);
printf(" student age: %d\n", node->record->student_age);
printf("\n");}
In the structure declaration of student_record
char first_name;
char last_name;
indicate first_name and last_name are two characters and not character arrays(ie. strings)
When using printf("%s", ELEMENT) , %s requires the memory address of the character array ie. pointer(char *) but since you passed a character instead, it's leading to a syntax error.
To fix your code, edit your structure declaration to make it either a static array of fixed length or dynamically allocate memory to the character pointer in your function.
Try in this way:
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<string.h>
struct student_record {
int student_id;
int student_age;
char first_name;
char last_name;
};
struct student_record_node {
struct student_record* record;
struct student_record_node* next;
struct student_record_node* prev;
};
void printNode(struct student_record_node *node){
printf("Struct student_record_node: \n");
printf(" student first_name: %c\n", node->record->first_name);
printf(" student last_name: %c\n", node->record->last_name);
printf(" student id: %d\n", node->record->student_id);
printf(" student age: %d\n", node->record->student_age);
printf("\n");
}
int main()
{
struct student_record_node* a = (student_record_node*)malloc(sizeof(student_record_node));
a->record = (student_record*)malloc(sizeof(student_record));
a->next = NULL;
a->prev = NULL;
a->record->first_name = 'f';
a->record->last_name = 'l';
a->record->student_age = 10;
a->record->student_id = 99;
printNode(a);
free(a);
return 0;
}
If you want to set name as string then use char* instead of char and format specifier as %s instead of %c.

How to sort a linkedlist in C programming?

So I am trying to sort a linked list, from small to big based on the name. It sorts it but it is sorting it the reverse or wrong way.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//declaring a struct
struct node {
char *name;
int num;
struct node *next;
};
struct node *list=NULL;
/*
* insert()
*/
struct node *insert(char word2[], int val){
struct node *tmp;
tmp = malloc(sizeof(struct node));
if(tmp ==NULL){
fprintf(stderr, "out of memory\n");
exit(1);
}
tmp->name = strdup(word2);
tmp->num = val;
tmp->next = list;
list = tmp;
return tmp;
}//read string
void print(){
struct node *ptr;
for(ptr= list; ptr!=NULL; ptr = ptr->next){
printf(" %s/%d\n", ptr->name, ptr->num);
}//for loop
}//print
void sort(){
struct node *ptr1, *ptr2;
char *tmp;
for(ptr1 = list; ptr1!=NULL; ptr1 = ptr1->next){
for(ptr2 = ptr1->next; ptr2!=NULL; ptr2 = ptr2->next){
if(strcmp(ptr1->name, ptr2->name)>0){
//ptr1->name is "greater than" ptr2->name - swap them
tmp = ptr1->name;
ptr1->name = ptr2->name;
ptr1->name = tmp;
}
}
}
}//sort
int main (){
char buff[81];
int status=0;
int len;
char word1[20];
char word2[20];
int val;
// char word3[20];
while(fgets(buff, 81, stdin)>0){
len = strlen(buff);
if(buff[len-1]!='\n'){
fprintf(stderr,"Error: string line length was too long\n");
exit(1);
}
sscanf(buff, "%s %s %d", word1, word2, &val);
if(strcmp(word1, "insert")==0){
insert(word2, val);
sort();
}else if(strcmp(word1, "print")==0){
print();
}else{
}
}//while loop
return status;
}
This is what my input looks like when I run it.
"insert a 1"
"insert b 2"
"insert c 3"
"print"
output
c/3
b/2
a/1
If have tried changing my sort method condition but it keeps sorting it the wrong way. I can't seem to find the bug. Any help will be greatly appreciated. But my output is supposed to look like this
Desired output
a/1
b/2
c/3
If you sort after every insert you do not need the full bubble-sort, just one round.
void sort()
{
struct node *ptr1 = list;
char *tmpname;
int tmpnum;
while (ptr1->next != NULL) {
if (strcmp(ptr1->name, ptr1->next->name) > 0) {
// swap content in this case, not the nodes
tmpname = ptr1->name;
tmpnum = ptr1->num;
ptr1->name = ptr1->next->name;
ptr1->num = ptr1->next->num;
ptr1->next->name = tmpname;
ptr1->next->num = tmpnum;
}
ptr1 = ptr1->next;
}
}

Resources