How to count the number of collisions in hash table? - c

Here's the task: "Develop a program for the formation and processing of hash tables, built on the principle of open addressing (private hashing). Practical evaluation of hash tables for the set structure, including the data key N-bit digital code (N >= 10). Explore two probing methods: linear and quadratic. Analyze and calculate the results obtained, first of all, the occurrence of collisons and the search time data for different indicators table coverage ratios"
???For some reason I can't do the last one. I can't count collisions and their output in any way, and calculate the search time. Suggest ideas for the algorithm, plz???
Here`s code:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN 20
typedef struct inform {
char* key, * name;
} INFO;
typedef struct hash_table {
int count, size;
INFO** array;
}HTAB;
INFO* New_Item(char* key, char* name)
{
INFO* result = (INFO*)malloc(sizeof(INFO));
result->key = key;
result->name = name;
return result;
}
void free_item(INFO* item)
{
if (item != NULL)
free(item);
}
HTAB* NewHTAB(int size)
{
HTAB* result = (HTAB*)malloc(sizeof(HTAB));
result->count = 0;
result->size = size;
result->array = (INFO**)malloc(sizeof(INFO*) * size);
memset(result->array, NULL, sizeof(INFO*) * size);
return result;
}
void free_hash_table(HTAB* table)
{
if (table != NULL) {
for (int i = 0; i < table->size; i++) {
INFO* item = table->array[i];
if (item != NULL) free_item(item);
}
free(table->array);
free(table);
}
}
int ht_hasItem(HTAB* table, int idx)
{
return table->array[idx] != NULL;
}
int ht_IsFull(HTAB* table)
{
return table->count == table->size;
}
int Hash_Code(int key, int size)
{
return key % size;
}
int Insert(HTAB* table, char* keycpy, char* namecpy)
{
int result = 0;
char* key = _strdup(keycpy);
char* name = _strdup(namecpy);
if (ht_IsFull(table)) printf("Hash table is FULL!!!");
else {
INFO* item = New_Item(key, name);
int idx = Hash_Code(atoi(key), table->size);
//int h = 1;
while (ht_hasItem(table, idx)) {
idx = Hash_Code(idx + 1, table->size);
}
//idx = Hash_Code(idx + (h*h), table->size);
//h++;
table->array[idx] = item;
table->count++;
}
return result;
free(key);
free(name);
}
void Display(HTAB* table)
{
printf("-------------------------------------------------\n");
for (int i = 0; i < table->size; i++) {
if (ht_hasItem(table, i)) {
INFO* item = table->array[i];
printf(" %d\t| %s\t| %s \t|\n", i, item->key, item->name);
printf("-------------------------------------------------\n");
}
else {
printf(" %d\t| ---\t| \t---\t\t|\n", i);
printf("-------------------------------------------------\n");
};
}
printf("\n");
}
int Search(HTAB* table, char* key)
{
int result = -1;
int idx = Hash_Code(atoi(key), table->size);
// int h = 1;
while (ht_hasItem(table, idx)) {
if (strcmp(table->array[idx]->key, key) == 0) {
result = idx;
break;
}
else idx = Hash_Code(idx + 1, table->size);
//idx = Hash_Code(idx + (h*h), table->size);
//h++;
}
return result;
}
INFO* Remove(HTAB* table, char* key)
{
INFO* result = NULL;
int idx = Search(table, key);
if (idx != -1) {
result = table->array[idx];
table->array[idx] = NULL;
table->count--;
}
return result;
}
int main() {
int itemIdx = 0;
INFO* item = NULL;
HTAB* table = NewHTAB(30);
char name[LEN], key[LEN];
int choice = 0, c;
system("chcp 1251");
FILE* ftxt;
if (!(ftxt = fopen("RGR_2_AP.txt", "r"))) {
puts("\n File not found...\n");
return 0;
}
while (fscanf(ftxt, "%s%s", name, key) == 2)
Insert(table, key, name);
printf("\n Іndex\t| Кey\t| \t NAME\t\t|\n");
Display(table);
do {
printf("MENU-: \n1.Insert new item"
"\n2.Search item"
"\n3.Delet item"
"\n\n Please choose one point-:");
scanf_s("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter name: ");
rewind(stdin);
gets_s(name);
printf("\nВведіть ключ: ");
gets_s(key);
while (strlen(key) < 10) {
printf("\nWrong key");
printf("\nTry again: ");
gets_s(key);
}
Insert(table, key, name);
printf("\n");
Display(table);
break;
case 2:
printf("\nEnter key: ");
rewind(stdin);
gets_s(key);
while (strlen(key) < 10) {
printf("\nWrong key");
printf("\nTry again: ");
gets_s(key);
}
itemIdx = Search(table, key);
if (itemIdx != -1) {
item = table->array[itemIdx];
printf("Item found: (%d, %s, %s)\n", itemIdx, item->key, item->name);
}
else printf("Item not found\n");
break;
case 3:
printf("\nEnter key: ");
rewind(stdin);
gets_s(key);
while (strlen(key) < 10) {
printf("\nWrong key");
printf("\nTry again: ");
gets_s(key);
}
Remove(table, key);
Display(table);
break;
default:
printf("Wrong Input\n");
}
printf("\n Do you want continue(enter 1 if yes)?-:\t");
scanf_s("%d", &c);
} while (c == 1);
free_hash_table(table);
printf("End...\n");
return 0;
}

You could add variables which count collisions in the Insert and Search methods, as well as the run time. You may need to return a list in that case, with the first element being the index, second being the # of collisions, and third being the run time.
Use the chrono library to time your functions.

Related

Why strcmp does not return 0?

I have a small program to handle a list of rabbits (name, district, participation count) stored in an array of pointers (Rabbit** iterator). I'd like to implement the following methods: add, delete and modify a rabbit, list all the rabbits or list by district.
When I compare for example the name of the rabbits in the list with strcmp() it doesn't return 0 when the names are equal. How can I solve this problem?
The Rabbit struct:
typedef struct Rabbit {
char* name;
char* district;
unsigned part_count;
} Rabbit;
The delete method:
bool delete_rabbit(char* delete_name)
{
for (unsigned i = 0; i < size; ++i) {
if (iterator[i] != NULL && strcmp(iterator[i]->name, delete_name) == 0) {
free(iterator[i]);
iterator[i] = NULL;
count--;
return true;
}
}
return false;
}
The list by district method:
void list_by_district(char* district)
{
unsigned counter = 0;
for (unsigned i = 0; i < size; ++i) {
if (iterator[i] != NULL && strcmp(iterator[i]->district, district) == 0) {
counter++;
printf("\n%u. Rabbit:\n", counter);
printf("Name: %s\nDistrict: %s\nParticipation count: %u\n", iterator[i]->name, iterator[i]->district, iterator[i]->part_count);
}
}
}
The modify method is similar to the delete method except it only changes the values.
The corresponding code snippets from main:
Rabbit** iterator;
unsigned size = 10, count = 0;
int main()
{
iterator = (Rabbit**)malloc(sizeof(Rabbit*) * 10);
...
do {
...
switch (input) {
case 'a':
if (count == size) iterator = allocate_more_memory();
...
iterator[count++] = add_rabbit(new_name, new_district, new_part_count);
break;
case 'd':
if (size == count + 6) iterator = allocate_less_memory();
do {
printf("Enter name to be deleted: ");
scanf("%[^\n]", delete_name);
getchar();
if (strlen(delete_name) >= 30) printf("Name only has 30 or less characters!\n");
} while (strlen(delete_name) >= 30);
if (!delete_rabbit(delete_name)) printf("\nThere's no rabbit in the list with this name.\n");
break;
...
}
} while (input != 'x');
...
free(iterator);
return 0;
}
EDIT:
The add method:
Rabbit* add_rabbit(char* new_name, char* new_district, unsigned new_part_count)
{
Rabbit* new_rabbit = (Rabbit*)malloc(sizeof(Rabbit));
if (new_rabbit) {
new_rabbit->name = (char*)malloc((strlen(new_name) + 1) * sizeof(char));
new_rabbit->district = (char*)malloc((strlen(new_district) + 1) * sizeof(char));
strcpy(new_rabbit->name, new_name);
strcpy(new_rabbit->district, district);
new_rabbit->part_count = new_part_count;
}
return new_rabbit;
}
The allocate less memory method:
Rabbit** allocate_less_memory()
{
Rabbit** new_iterator = (Rabbit**)malloc(sizeof(Rabbit*) * (size - 5));
if (new_iterator) {
unsigned counter = 0;
for (unsigned i = 0; i < size; ++i) {
if (iterator[i] != NULL) {
new_iterator[counter++] = iterator[i];
}
}
size -= 5;
free(iterator);
return new_iterator;
}
return NULL;
}

I have got a problem with reading binary file into array of structures in c

Here is part of my code:
Here I want to transfer already saved .bin file into a new database structure student s, but it is not transferring more than one member of a structure.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[20];
int date;
int month;
int year;
int id;
int pnum;
}student;
int count = 0;
void swap(student* s1, student* s2) {
student* temp;
temp = s1;
s1 = s2;
s2 = temp;
}
void sort(student* s) {
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (strcmp((s + i)->name, (s + j)->name) > 0) {
student temp = *(s + i);
*(s + i) = *(s + j);
*(s + j) = temp;
}
}
}
}
void addInf(student* s) {
printf("\t==================================Adding information=====================================\n\n");
printf("\t\tPlease input following information: \n");
printf("\tName: ");
scanf("%s", (s + count)->name);
printf("\tDate of birth (yyyymmdd): ");
scanf("%4d%2d%2d", &(s + count)->year, &(s + count)->month, &(s + count)->date);
printf("\tStudent ID: ");
scanf("%d", &(s + count)->id);
printf("\tPhone number: ");
scanf("%d", &(s + count)->pnum);
count++;
printf("\tEntry succeded.\n");
printf("\t=========================================================================================\n\n");
}
void print(student* s) {
printf("\t\tName: %s\n", s->name);
printf("\t\tBidthday: %d/%02d/%02d\n", s->year, s->month, s->date);
printf("\t\tID: %d\n", s->id);
printf("\t\tPhone number: %d\n", s->pnum);
}
void delInf(student* s, int n) {
int com;
printf("\t=================================Deleting information====================================\n\n");
printf("\t=========================================================================================\n\n");
char name[20];
printf("\t\tPlease input name of the student that you want to delete: ");
scanf("%s", &name);
for (int i = 0; i < count; i++) {
if ((strcmp(name, (s + i)->name)) == 0) {
printf("\t\tInformation that you want to delete\n");
print((s + i));
for (int j = i; j < count; j++) {
*(s + i) = *(s + i + 1);
count--;
printf("\t\tInformation was succesfully deleted.\n\n");
}
}
}
}
void searchByID(student* s) {
int key;
printf("\t======================================Searching by ID====================================\n\n");
printf("\t\tEnter ID: ");
scanf("%d", &key);
printf("\t=========================================================================================\n\n");
int i;
for (i = 0; i < count; i++) {
if (key == (s + i)->id) {
break;
}
}
print((s + i));
}
void searchByName(student* s) {
char key[20];
int i;
int size, check = 0;
printf("\t======================================Searching by Name==================================\n\n");
printf("\t\tEnter Name: ");
scanf("%s", &key);
printf("\t=========================================================================================\n\n");
for (i = 0; i < count; i++) {
if (strcmp(key, (s + i)->name) == 0) {
print((s + i));
}
}
}
void searchByBirthDate(student* s) {
int key, command;
int i;
printf("\t================================Searching by Birthdate================================\n\n");
printf("\t\t1.By Date\t\t 2.By Month\t\t 3.By Year\t\t 4.By All\n");
printf("\t\tCommand: ");
scanf("%d", &command);
printf("\t=========================================================================================\n\n");
if (command == 1) {
printf("Enter date: ");
scanf("%2d", &key);
printf("\t\tStudent with same date\n");
for (i = 0; i < count; i++) {
if (key == (s + i)->date) {
printf("\t\t---------%d----------\n\n", i + 1);
print((s + i));
}
}
}
if (command == 2) {
printf("\t\tEnter month: ");
scanf("%2d", &key);
printf("\t\tStudent with same month\n");
for (i = 0; i < count; i++) {
if (key == (s + i)->month) {
printf("\t\t---------%d----------\n\n", i + 1);
print((s + i));
}
}
}
if (command == 3) {
printf("\t\tEnter year: ");
scanf("%4d", &key);
printf("\t\tStudent with same year\n");
for (i = 0; i < count; i++) {
if (key == (s + i)->year) {
printf("\t\t---------%d----------\n\n", i + 1);
print(s + i);
}
}
}
if (command == 4) {
int yy, mm, dd;
printf("\t\tEnter birthdate: ");
scanf("%4d%2d%2d", &yy, &mm, &dd);
for (i = 0; i < count; i++) {
if (yy == (s + i)->year && mm == (s + i)->month && dd == (s + i)->date) {
break;
}
}
print(s + i);
}
}
void printTable(student* s) {
printf("\t============================================Table========================================\n\n");
printf("\t\tName\t\t\tBirthday\t\t\tStudent ID\t\t\tPhone number\n\n");
for (int i = 0; i < count; i++) {
printf("\t%d. %s\t\t\t\t%d/%d/%d\t\t\t%d\t\t\t0%d\n\n", i + 1, (s + i)->name, (s + i)->year, (s + i)->month, (s + i)->date, (s + i)->id, (s + i)->pnum);
}
printf("\t=========================================================================================\n\n");
}
void search(student* s) {
printf("\t=========================================Search==========================================\n\n");
printf("\t\tAvailable commands: \n");
printf("\t\t1. Search by name\t\t\t2. Search by ID\n\t\t3. Search by birthday\n");
printf("\t=========================================================================================\n\n");
printf("\t\tPlease choose command: ");
int com;
scanf("%d", &com);
switch (com) {
case 1: searchByName(s);
break;
case 2: searchByID(s);
break;
case 3: searchByBirthDate(s);
break;
}
}
void menu() {
printf("\n\t======================================MENU===============================================\n");
printf("\t\tAvailable commands: \n");
printf("\t\t1. Add Student\t\t\t2.Delete student\n\t\t3. Find student\t\t\t4. Table of all students\n");
printf("\t\t5. Transfer information from binary file\n\t\t6. Save information into binary file.\n\t\t0. Exit\n\n");
printf("\t=========================================================================================\n\n");
printf("\t\tPlease choose command: ");
}
int main() {
FILE* fp;
FILE* fpr;
printf("\t\tEnter a name of binary file that you want to create: ");
char filename[20];
scanf("%s", &filename);
strcat(filename, ".bin");
fp = fopen(filename, "ab");
if (fp == NULL) {
printf("\t\tUnable to open the file.\nError\n");
exit(1);
}
else printf("\t\t\tFile %s successfuly created\n\n", filename);
int iCount;
int n, c;
student* s;
printf("\t\tPlease enter number of students: ");
scanf("%d", &n);
printf("\n\n");
s = (student*)calloc(n, sizeof(student));
int quit = 1;
while (quit) {
menu();
scanf("%d", &c);
printf("\n");
switch (c) {
case 0:
quit = 0;
break;
case 1:
addInf(&s);
break;
case 2:
delInf(&s, n);
break;
case 3:
search(&s);
break;
case 4:
if (count == 0) printf("\t\tThere is no any given information yet.\n\n");
else printTable(&s);
break;
case 5:
printf("\t\tEnter a name or path of file that you want to open: ");
char readfilename[30];
scanf("%s", &readfilename);
strcat(readfilename, ".bin");
fpr = fopen(readfilename, "rb+");
if (fpr == NULL) {
printf("\t\tUnable to open the file.\nError\n");
break;
}
else printf("\t\tFile %s successfuly opened for reading\n", readfilename);
printf("\t\t\ttransfering binary data from %s into database\n", readfilename);
while ((fread(&s, sizeof(student), 1, fpr)) == 1) {
count++;
}
printf("\t\t%d student information was successfuly transferred\n", count);
break;
case 6:
iCount = fwrite(&s, sizeof(student), count, fp);
if (iCount != count) printf("Information could be missed in %s file\n", filename);
else printf("\t\tAll information was successfuly copied into %s file", filename);
}
sort(&s);
}
fclose(fp);
return 0;
}
First of all, enable warnings when compiling, and follow up on them!
This should tell you that &s is wrong in every place where you used it.
This causes your program to suffer from undefined behavior, which is a total pest when trying to debug your program!
Now then, on to the code that reads students from file:
while ((fread(s, sizeof(student), 1, fpr)) == 1) {
count++;
}
Every student is read into the same memory area (pointed to by s). They overwrite each other, leaving only the last one read. Try s + count instead of s:
while ((fread(s + count, sizeof(student), 1, fpr)) == 1) {
count++;
}

C programming using data structures (Priority Queue) storing and displaying a character and integer together int the queue

#include <stdio.h>
#include <stdlib.h>
#define MAX 5
void insert_by_priority(int);
void delete_by_priority(int);
void create();
void check(int);
void display_pqueue();
int pri_que[MAX];
int front, rear;
void priority()
{
int n, ch;
char v[20];
printf("\n1 - Insert");
printf("\n2 - Delete");
printf("\n3 - Display");
printf("\n4 - Exit");
create();
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter age to be inserted : ");
scanf("%d",&n);
printf("\nEnter name:");
scanf("%s",&v);
insert_b
y_priority(n);
printf("%s");
break;
case 2:
printf("\nEnter age to delete : ");
scanf("%d",&n);
delete_by_priority(n);
break;
case 3:
display_pqueue();
break;
case 4:
exit(0);
default:
printf("\nChoice is incorrect, Enter a correct choice");
}
}
}
void create()
{
front = rear = -1;
}
void insert_by_priority(int data)
{
if (rear >= MAX - 1)
{
printf("\nQueue overflow no more elements can be inserted");
return;
}
if ((front == -1) && (rear == -1))
{
front++;
rear++;
pri_que[rear] = data;
return;
}
else
check(data);
rear++;
}
void check(int data)
{
int i,j;
for (i = 0; i <= rear; i++)
{
if (data >= pri_que[i])
{
for (j = rear + 1; j > i; j--)
{
pri_que[j] = pri_que[j - 1];
}
pri_que[i] = data;
return;
}
}
pri_que[i] = data;
}
void delete_by_priority(int data)
{
int i;
if ((front==-1) && (rear==-1))
{
printf("\nQueue is empty no elements to delete");
return;
}
for (i = 0; i <= rear; i++)
{
if (data == pri_que[i])
{
for (; i < rear; i++)
{
pri_que[i] = pri_que[i + 1];
}
pri_que[i] = -99;
rear--;
if (rear == -1)
front = -1;
return;
}
}
printf("\n%d not found in queue to delete", data);
}
void display_pqueue()
{
if ((front == -1) && (rear == -1))
{
printf("\nQueue is empty");
return;
}
for (; front <= rear; front++)
{
printf(" %d ", pri_que[front]);
}
front = 0;
}
I have this code on priority queue but i am unable to insert a string alongside the integer like a sorted record i.e
AGE | NAME
78 | abcd
75 | bcdfe
.............etc
I tried using scanf statements but to no avail it prints it seperately or do i have to use emplace?what will be the code changes? but how to implement using user input?Or do i have to implement another data structure? if yes then how?

Array of singly linked list won't delete node

I have an array[4] where each index of the array has a singly linked list that holds the following information: name, size. The switch statement controls what index the information will go into according to the size of the party.
Problem: When trying to delete a node according to the size (user inputs) the node will not delete.
I know that all of the cases of deletion have the proper syntax but I cannot figure out why my node will not delete. Appreciate any help.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
char name[20];
int size;
struct node *next;
}node;
node* head[4]={NULL,NULL,NULL,NULL};
node* tail[4]={NULL,NULL,NULL,NULL};
//
// proto's
//
void add_party(int, char name[], int size);
void delete_party(char name[], int size);
void list_parties(void);
void change_p_size(char name[], int size);
//
// main function
//
int main()
{
int x;
while (1)
{
fflush(stdin);
printf("\n\nEnter 1 to add a party\nEnter 2 to remove a party\nEnter 3 for the list of the party\nEnter 4 to change party size.\nEnter 5 to quit.\n\n");
// user interface
scanf("%d",&x);
switch(x)
{
char name[20]; //local variables
int size;
case 1:
printf("\nParty Name: ");
scanf("%s", name);
printf("\nParty Size: ");
scanf("%d", &size);
if(size == 0)
{
printf("\nThat is not a valid command. Party not added!\n");
}
if(size >= 1 && size <= 2)
{
add_party(0, name, size);
}
else if(size >= 3 && size <= 4)
{
add_party(1, name, size);
}
else if(size >= 5 && size <= 6)
{
add_party(2, name, size);
}
else if(size >= 7)
{
add_party(3, name, size);
}
break;
case 2:
printf("\nSize of party to delete: ");
scanf("%i", &size);
delete_party(NULL, size);
break;
case 3:
list_parties();
break;
case 4:
change_partysize();
break;
case 5:
exit(0);
default:
continue;
}
}
}
//
//add function
//
void add_party(int h, char *name, int size)
{
//create a new node
int i=0;
int breaker = 0;
node *p;
node *new_item;
new_item = (node *)malloc(sizeof(node)); // allocate memory the size of the struct
strcpy(new_item->name,name);
new_item->size = size;
if(head[h] == NULL && tail[h] == NULL) // if an empty list, create a head and tail
{
head[h] = new_item;
tail[h] = head[h];
new_item->next = NULL;
return;
}
//traversal
for(i=0; i<4; i++)
{
p = head[i];
while(p != NULL)
{
//check that no repeating names. delete nodes that do have repeating names
if(strcmp(p->name,name) == 0)
{
printf("\nSorry, that name is already taken\n");
free(new_item);
return;
}
p = p->next; //go to the next node in the list
}
}
tail[h]->next = new_item;
new_item->next = NULL;
tail[h] = new_item;
}
//
//delete function
//
void delete_party(char *name, int size)
{
int i=0;
int breaker = 0;
node *p;
node *previous;
if(name != NULL)
{
for(i=0; i<4; i++)
{
p = previous = head[i]; //make sure previous trails behind head
while(p != NULL)
{
int c = (strcmp(p->name,name)==0);
if(c==0)
{
breaker = 1;
break;
}
else
previous = p;
p = p -> next;
}
if(breaker==1)
break;
}
}
else
{
int group = -1;
if(size == 1 || size == 2)
{
group = 0;
}
if(size == 3 || size == 4)
{
group = 1;
}
if(size == 5 || size == 6)
{
group = 2;
}
if(size >= 7)
{
group = 3;
}
for(i = group; i > -1; i--)
{
node *p = head[i];
node *previous = head[i];
while(p != NULL)
{
if(p <= size)
{
breaker = 1;
break;
}
else
{
previous = p;
p = p-> next;
}
}
if(breaker)
break;
}
}
if(p == NULL)
return;
if(head[i] == tail[i] && head[i] != NULL) // case 1, empty list
{
printf("\nList is empty!\n");
return;
}
else if(p == tail[i] && p == head[i]) // case 2, one element
{
head[i] = NULL;
tail[i] = NULL;
free(p);
}
else if(p == head[i]) // case 3, delete from the head
{
head[i] = head[i] -> next;
tail[i] = NULL;
free(p);
}
else if(p == tail[i]) // case 4, delete from tail
{
tail[i] = previous;
tail[i] -> next = NULL;
free(p);
}
else // case 5, delete from middle
{
previous -> next = p -> next;
free(p);
}
}
//
// list function
//
void list_parties(void)
{
int i = 0;
node *p=head;
for(i=0; i<4; i++)
{
p=head[i];
while(p != NULL)
{
printf("\n\n%s, %d\n\n", p->name, p->size);
p=p->next;
}
}
}
//
// change function
//
void change_partysize(char *name, int size)
{
int absolute_value = 0;
int comparison = 0;
int current_size = 0;
printf("\nWhat name is your party under?\n");
scanf("%s", name);
//check if the name
printf("\nWhat would you like to change the size to?\n");
scanf("%d", &size);
node *p;
while(p != NULL)
{
if(p->name == name) //new size falls into same range as the size coorelating to the name
{
current_size = p->size;
absolute_value = abs(size - current_size);
comparison = size - current_size;
if(current_size > 7 && size > 7)
{
current_size = size;
return;
}
else if(absolute_value >= 1)
{
//delete the node's value but not the name
delete_party(NULL, size);
//insert node with new name & dif size
add_party(NULL, name, size);
}
else
{
printf("\nYou did not enter a different party size\n");
return;
}
}
}
}
You're declaring new variables p and previous inside the for loop when you delete by size. So when the code after the loop uses these variables, it's using the uninitialized variables declared at the top of the function. Get rid of the declarations and just assign the variables.
Also, if (p <= size) appears to be a typo for if (p->size <= size). I'm surprised you didn't get a compiler warning for that.
You can also replace the if(breaker) check with a test in the for header.
for(i = group; !breaker && i > -1; i--)
{
p = head[i];
previous = head[i];
while(p != NULL)
{
if(p->size <= size)
{
breaker = 1;
break;
}
else
{
previous = p;
p = p-> next;
}
}
}

Stack of strings

Hi i have program here that accept int as value. i wanted to translate it to accept strings in array then. i have read about using struct but i couldnt get into it. i hope someone can help me getting into that without using struct i dont know where to start i want to keep this lines of code.
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int top = 0;
int *stack = NULL;
int size = 0;
main()
{
int opt, num;
char cont[] = { 'y' };
clrscr();
/* <start Declaring Stack Size { */
printf("Stacking Program");
printf("\n\nData Size: ");
scanf("%d", &size);
printf("\n");
/* } end> */
/* <start Allocates size of stack { */
if(size > 0)
{
stack = malloc(size * sizeof(int));
if(stack == NULL)
{
printf("ERROR: malloc() failed\n");
exit(2);
}
}
else
{
printf("ERROR: size should be positive integer\n");
exit(1);
}
/* } end> */
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
/* <start Main Menu { */
printf("Stacking Program");
printf("\n\nData Size: %d\n\n", size);
printf("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
scanf("%d", &opt);
printf("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top==size)
{
printf("You can't push more data");
}
else
{
printf("Enter data for Stack[%d]: ", top+1);
scanf("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
printf("Your choice is not on the list.");
break;
}
/* } end> */
printf("\n\nDo you want continue\(Y\/N\)?");
scanf("%s", &cont[0]);
}
free(stack);
}
pop()
{
int a;
loading();
if(top <= 0)
{
printf("Stack empty.");
return 0;
}
else
{
top--;
a=stack[top];
printf("\(Stack[%d] = %d\) removed.", top+1, a);
}
}
push(int a)
{
stack[top]=a;
top++;
loading();
}
pick()
{
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
printf("\(Stack[%d] = %d\) is the last data.", top, stack[top-1]);
}
}
view()
{
int i;
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
for(i=0;i<top;i++)
{
printf("Stack[%d] = %d\n", i+1, stack[i]);
}
}
}
loading()
{
float i, x;
float load;
int loadarea[] = { 5000, 10000, 15000, 20000, 25000, 30000 };
int percentLoad;
x=0;
load=0;
percentLoad = loadarea[random(5)];
gotoxy(26,11);
printf("[");
for(i=0;i<25;i++)
{
x = i+27;
gotoxy(x, 11);
printf("=");
delay(percentLoad);
gotoxy(51,11);
printf("]");
gotoxy(53,11);
load=(i/25)*104.5;
if(load>100)
load = 100.00;
printf("%.2f\%",load);
}
delay(60000);
for(i=0;i<60;i++) {
printf("\b \b");
}
printf("\n");
}
Easiest way is to convert your stack to store char* instead of int.
char **stack;
stack = malloc( size * sizeof(char*) );
Now, your push operation will accept a char* from some buffer that is storing the string that was just input, duplicate it with strdup, and store that new pointer in the stack.
typedef enum {
STACK_MEM_ERROR = -1,
STACK_FULL = 0,
STACK_OK = 1
} StackStatus;
StackStatus push(const char *str)
{
char *newstr;
if( top >= size ) return STACK_FULL;
newstr = strdup(str);
if( newstr == NULL ) return STACK_MEM_ERROR;
stack[top++] = newstr;
return STACK_OK;
}
When you pop a string, you just get a pointer.
char *pop()
{
if( top == 0 ) return NULL;
return stack[--top];
}
You are responsible for freeing that memory when you are finished with the pointer (by calling free).
char * val;
while( NULL != (val = pop()) )
{
printf( "I popped: %s\n", val );
free(val);
}

Resources