c program crashes when calling a function - c

i was trying to create a program that manages car fixing records,and everything was working fine until case 6 of this code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int day;
int month;
int year;
}date;
typedef struct{
char pie_name[50];
int pie_num;
float pie_price;
}pie_st;
typedef struct{
long car_num;
char car_type[20];
char car_colour[20];
char owner_name[50];
long phone_num;
}own_cars_st;
typedef struct{
int management_num;
long car_num;
date date_of_management;
int pieces_num;
pie_st pie_rec[1000];
float management_fees;
float total_price;
}management_st;
void check_file(FILE *ptf);
void add_car_rec();
void add_management_rec();
int delete_car_rec(long search);
int search_own(char owner[]);
int car_man(long search);
int main(){
int option,c=0,found=1;
long search;
char owner[50];
while(c==0)
{
printf("\nplease enter your choice:\n");
printf("1.add new car record\n");
printf("2.add new car management record\n");
printf("3.delete a car record by number\n");
printf("4.view all car numbers for a specific owner\n");
printf("5.display all management records\n");
printf("6.view a specific car's management records and the total cost\n");
printf("7.view the most used gear piece's number\n");
printf("8.view a list of all cars that had management after a specific date\n");
printf("9.view all cars with changed tires\n");
printf("10.exit\n");
scanf("%d",&option);
switch(option)
{
case 1:
add_car_rec();
break;
case 2:
add_management_rec();
break;
case 3:
printf("please enter the number of the car you want to delete its number:\t");
scanf("%ld",&search);
found=delete_car_rec(search);
if(found==1)
printf("there's no record available for this number!\n");
else
printf("record has been deleted!\n");
break;
case 4:
printf("please enter the name of the owner:\t");
fflush(stdin);
scanf("%[^\n]s",owner);
found=search_own(owner);
if(found==1)
printf("owner was not found!\n");
break;
case 5:
break;
case 6:
printf("please enter the number of the car you want to view its management records:\t");
scanf("%ld",&search);
printf("7");
car_man(search);
printf("8");
if(found==1)
printf("this car number has no management records!\n");
break;
case 7:
break;
case 8:
break;
case 9:
break;
case 10:
c=10;
break;
default:
printf("please choose one of the available options\n");
}
}
return 0;
}
void add_car_rec(){
own_cars_st new_car,old_cars[100];
printf("please enter the car information:\n");
printf("car number:\t");
scanf("%ld",&new_car.car_num);
printf("car type:\t");
fflush(stdin);
scanf("%[^\n]s",new_car.car_type);
printf("car colour:\t");
fflush(stdin);
scanf("%[^\n]s",new_car.car_colour);
printf("owner name:\t");
fflush(stdin);
scanf("%[^\n]s",new_car.owner_name);
printf("phone number:\t");
scanf("%ld",&new_car.phone_num);
FILE *ptf;
int n=0,i,j,fc;
ptf=fopen("owners and cars.bin","ab+");
if(ptf!=NULL){
fseek(ptf,0,2);
fc=ftell(ptf);
rewind(ptf);
if(fc==0)
{
fwrite(&new_car,sizeof(own_cars_st),1,ptf);
fclose(ptf);
}
else{
while(1==fread(&old_cars[n],sizeof(own_cars_st),1,ptf))
{
n++;
}
for(i=0;i<n+1;i++)
{
if(new_car.car_num<old_cars[i].car_num)
{
for(j=n+1;j>i;j--)
{
old_cars[j]=old_cars[j-1];
}
break;
}
}
old_cars[i]=new_car;
fclose(ptf);
ptf=fopen("owners and cars.bin","wb");
check(ptf);
for(i=0;i<n+1;i++)
{
fwrite(&old_cars[i],sizeof(own_cars_st),1,ptf);
}
fclose(ptf);
}
}
}
void add_management_rec(){
FILE *ptf;
int i,count=0,empty;
float sum=0;
management_st new_manage_rec,last_manage_rec;
printf("please enter the new management record information:\n");
printf("fixed car's number:\t");
scanf("%ld",&new_manage_rec.car_num);
printf("date of management:\n");
printf("day:\t");
scanf("%d",&new_manage_rec.date_of_management.day);
printf("month:\t");
scanf("%d",&new_manage_rec.date_of_management.month);
printf("year:\t");
scanf("%d",&new_manage_rec.date_of_management.year);
printf("the number of the used pieces types:\t");
scanf("%d",&new_manage_rec.pieces_num);
printf("please enter each type's information:\n");
for(i=0;i<new_manage_rec.pieces_num;i++)
{
printf("piece #%d\n",i+1);
printf("piece name:\t");
scanf("%s",new_manage_rec.pie_rec[i].pie_name);
printf("number of used pieces:\t");
scanf("%d",&new_manage_rec.pie_rec[i].pie_num);
printf("piece's price:\t");
scanf("%f",&new_manage_rec.pie_rec[i].pie_price);
sum+=new_manage_rec.pie_rec[i].pie_price*(float)new_manage_rec.pie_rec[i].pie_num;
}
printf("management fees:\t");
scanf("%f",&new_manage_rec.management_fees);
new_manage_rec.total_price=new_manage_rec.management_fees+sum;
ptf=fopen("management.bin","ab+");
if(ptf!=NULL)
{
fseek(ptf,0,2);
empty=ftell(ptf);
rewind(ptf);
if(empty==0){
new_manage_rec.management_num=1;
fwrite(&new_manage_rec,sizeof(management_st),1,ptf);}
else
{
fseek(ptf,-sizeof(management_st),2);
fread(&last_manage_rec,sizeof(management_st),1,ptf);
new_manage_rec.management_num=last_manage_rec.management_num+1;
fwrite(&new_manage_rec,sizeof(management_st),1,ptf);
}
}
fclose(ptf);
}
void check(FILE *ptf){
if(ptf==NULL)
{
printf("error!\n");
exit -1;
}
}
int delete_car_rec(long search){
FILE *ptf;
int count=0,i,j,f=1;
own_cars_st avai_cars[100];
ptf=fopen("owners and cars.bin","rb");
check(ptf);
while(fread(&avai_cars[count],sizeof(own_cars_st),1,ptf)==1)
{
count++;
}
fclose(ptf);
if(count==1)
{
if(search==avai_cars[0].car_num)
{
f=0;
ptf=fopen("owners and cars.bin","wb");
fclose(ptf);
}
}
else
{
for(i=0;i<count;i++)
{
if(search==avai_cars[i].car_num)
{
f=0;
for(j=i+1;j<count;j++)
{
avai_cars[i]=avai_cars[j];
}
}
}
ptf=fopen("owners and cars.bin","wb");
check(ptf);
for(i=0;i<count;i++)
fwrite(&avai_cars[i],sizeof(own_cars_st),1,ptf);
fclose(ptf);
}
return f;
}
int search_own(char owner[]){
FILE *ptf;
int found=1,count=0,i;
own_cars_st avai_cars[100];
ptf=fopen("owners and cars.bin","rb");
check(ptf);
while(1==fread(&avai_cars[count],sizeof(own_cars_st),1,ptf))
count++;
fclose(ptf);
for(i=0;i<count;i++)
{
if(strcmp(avai_cars[i].owner_name,owner)==0)
{
found=0;
printf("car#%d:\t%ld\n",i+1,avai_cars[i].car_num);
}
}
return found;
}
int car_man(long search){
printf("*\n");
FILE *ptf;
management_st avai_man[100];
int i,count=0,found=1,j;
float total_cost=0;
printf("0\n");
ptf=fopen("management.bin","rb");
check(ptf);
printf("1\n");
while(1==fread(&avai_man[count],sizeof(management_st),1,ptf))
count++;
fclose(ptf);
printf("2\n");
for(i=0;i<count;i++)
{
if(search==avai_man[i].car_num)
{
found=0;
printf("date of management:\n");
printf("day:\t");
printf("%d",avai_man[i].date_of_management.day);
printf("month:\t");
printf("%d",avai_man[i].date_of_management.month);
printf("year:\t");
printf("%d",avai_man[i].date_of_management.year);
printf("the number of the used pieces types:\t");
printf("%d",avai_man[i].pieces_num);
printf("please enter each type's information:\n");
for(j=0;j<avai_man[i].pieces_num;j++)
{
printf("piece #%d\n",i+1);
printf("piece name:\t");
printf("%s",avai_man[i].pie_rec[j].pie_name);
printf("number of used pieces:\t");
printf("%d",avai_man[i].pie_rec[j].pie_num);
printf("piece's price:\t");
printf("%f",avai_man[i].pie_rec[j].pie_price);
}
printf("management fees:\t");
printf("%f",avai_man[i].management_fees);
}
total_cost+=avai_man[i].management_fees;
}
printf("3\n");
printf("total cost for this car:\t%f",total_cost);
return found;
}
the program seems to crash when calling the function car_man,ive writted few printf to trace when the program crashes and it only reaches printf("7\n").
any help would be appreciated ^.^
p.s. there's no warnings or any thing in the compiler

management_st avai_man[1000];
That is a really big array to be creating on the stack; you may be running out of stack-space.
Consider moving the array to dynamically allocated memory, or making it a static.

Related

Removing nodes from middle of Linked List and infinite loop in C

I'm trying to create a linked list structure in C to allow a user to enter a list of direct debits with a description, then allow the user to select and delete any node. The solution I got from many sources, while researching, isn't working. No matter which node I choose, the latest one is always deleted.
Can anyone tell me where the problem in my code is?
It's also started throwing infinite loops of one node when printining the entire list
#define true 1
#define false 0
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Banknode {
float debit;
char description[100];
struct Banknode *next;
}Banknode;
struct Banknode *latestPtr = NULL;
int isEmpty(void);
void add(float fig, char info[100]);
float rmv(int n);
void allList();
void showMenu();
int main()
{
latestPtr = NULL;
int choice;
float deb;
char info[100];
int n;
//MENU
printf("\nWelcome to your DirectDebit management system");
printf("\nPlease select an option:");
printf("\n1. View Latest DirectDebit");
printf("\n2. View all DirectDebits");
printf("\n3. Add a DirectDebit");
printf("\n4. Remove a DirectDebit");
printf("\n5. Show menu");
printf("\n6. Exit\n");
while(choice != 6)
{
scanf("\n%d", &choice);
switch(choice)
{
case 1:
{
if(!isEmpty())
{
printf("\nThe latest DirectDebit is: \n%.2f for %s,\n", latestPtr->debit, latestPtr->description);
showMenu();
}
else
{
printf("\nAll DirectDebits have been removed.\n");
printf("To see the menu, select option 5,\n");
printf("Or to quit, select option 6.\n");
}
break;
}
case 2:
{
if(!isEmpty())
allList();
else
{
printf("\nYou have no DirectDebits\n");
printf("To see the menu, select option 5,\n");
printf("Or to quit, select option 6.\n");
}
break;
}
case 3:
{
printf("\nWhat is the amont of new DirectDebit?\n");
scanf("\n%f", &deb);
printf("\nPlease give a brief, unique description of the new DirectDebit\n");
fgets(info, 100, stdin);
scanf("%[^\n]%*c", info);
printf("\n Your DirectDebit amount is : %.2f", deb);
printf("\n And the description is: %s", info);
add(deb, info);
printf("\n");
showMenu();
break;
}
case 4:
{
if(!isEmpty())
{
if(latestPtr->next != NULL)
{
printf("\nPlease enter the number of the DirectDebit you wish to remove, by counting from the bottom up:\n");
allList();
scanf("\n%d", &n);
printf("\nRemoving DirectDebit\n");
printf("\n%.2f is removed from the list",rmv(n));
}
else
{
printf("\nAll DirectDebits have now been removed.\n");
printf("To see the menu, select option 5,\n");
printf("Or to quit, select option 6.\n");
latestPtr = NULL;
}
}
else
{
printf("\nYou have no DirectDebits\n");
printf("To see the menu, select option 5,\n");
printf("Or to quit, select option 6.\n");
}
break;
}
case 5:
{
showMenu();
break;
}
case 6:
printf("Thank you, Goodbye!\n");
exit(1);
break;
default:
printf("\nInvalid choice.\n");
showMenu();
break;
}
}
}
int isEmpty(void)
{
if(latestPtr == NULL)
return true;
else
return false;
}
void allList()
{
struct Banknode *scanPtr = NULL;
scanPtr = latestPtr;
printf("\nYour current DirectDebits are: \n");
while(scanPtr->next != NULL)
{
printf("%.2f for %s,\n",scanPtr->debit, scanPtr->description);
scanPtr = scanPtr->next;
}
printf("%.2f for %s,\n",scanPtr->debit, scanPtr->description);
}
void add(float fig, char info[100])
{
struct Banknode *newPtr = (struct Banknode*)malloc(sizeof(struct Banknode));
if (newPtr != NULL)
{
newPtr->debit = fig;
strcpy((newPtr->description), info);
newPtr->next = latestPtr;
latestPtr = newPtr;
}
else
{
printf("%.2f not inserted. No memory available.\n", fig);
}
free(newPtr);
}
float rmv(int n)
{
int len = 0, i;
struct Banknode *rmvPtr = latestPtr;
while (rmvPtr != NULL)
{
rmvPtr = rmvPtr->next;
len++;
}
if (len < n)
return -9999;
else
rmvPtr = latestPtr;
for (i = 1; i < len-n+1; i++)
rmvPtr = rmvPtr->next;
float j = latestPtr->debit;
latestPtr = latestPtr->next;
return j;
}
void showMenu()
{
printf("\nPlease select an option:");
printf("\n1. View Latest DirectDebit");
printf("\n2. View all DirectDebits");
printf("\n3. Add a DirectDebit");
printf("\n4. Remove a DirectDebit");
printf("\n5. Show menu");
printf("\n6. Exit\n");
}

How to display data that we entered from another function in C by using struct

I can't find the solution on how to view the data that we have entered before in a function that is used to enter information. Also, I'm using struct, not normal declaration and variable.
Here's the flow, I choose case 1 which will call addbook function where I will insert my data then later I will choose case 4 where the data that I just insert now supposed to be display on the screen but unfortunately it won't display the data. So, what should I do? It would be grateful if you guys could help me
This is my coding
struct book
{
char title[50];
char author[50];
int quantity;
int price;
};
struct book a;
void addbook();
//void searchbook();
//void deletebook();
void viewbook();
//void updatebook();
void returnfunc();
int main()
{
char choice;
do
{
printf("\n\n\t1.Add Book\n");
printf("\n\t2.Search Book\n");
printf("\n\t3.Delete Book\n");
printf("\n\t4.View Book\n");
printf("\n\t5.Update Book\n");
printf("\n\t6.Exit\n");
printf("\n\nPlease enter your choice :");
scanf("%d",&choice);
switch (choice)
{
case 1 :addbook();
break;
//case 2 :searchbook();
break;
//case 3 :deletebook();
break;
case 4 :viewbook();
break;
//case 5 :updatebook();
break;
case 6 :printf("THANK YOU !!");
break;
default :printf("Wrong Choice.Please enter Again");
break;
}
}
while(choice!=6);
return 0;
}
void addbook()
{
printf("\n============= PLEASE ADD NEW BOOK DETAILS ================");
int quantity;
FILE *fp;
printf("\n\nNumber of book to insert:");
scanf("%d", &quantity);
struct book a[quantity];
int i;
fp=fopen("Bibek.dat","ab+");
for(i=0;i<quantity;i++)
{
printf("Title:");
scanf("%s", &a[i].title);
printf("Author:");
scanf("%s", &a[i].author);
printf("Price:");
scanf("%d", &a[i].price);
printf("\n");
}
printf("\n\n---NEW BOOK DETAILS WAS SUCCESFULLY ADDED---\n\n");
}
//void searchbook()
//{
//printf("========SEARCH THE BOOK========");
//}
//void deletebook()
//{
//}
void viewbook(void)
{
FILE *fp;
int i=0,j;
system("cls");
printf("*********************************Book List*****************************");
printf(" TITLE AUTHOR QTY PRICE");
j=4;
fp=fopen("Bibek.dat","rb");
while(fread(&a,sizeof(a),1,fp)==1)
{
printf("%s",a.title);
printf("%s",a.author);
printf("%d",a.quantity);
printf("%d",a.price);
printf("\n\n");
j++;
i=i+a.quantity;
}
printf("Total Books =%d",i);
fclose(fp);
returnfunc();
}
void returnfunc(void)
{
{
printf(" Press ENTER to return to main menu");
}
a:
if(getch()==13) //allow only use of enter
main();
else
goto a;
}
//void updatebook()
//{
//}
The changes you need are rather easy and/or in the comments. Please try it. You can modify my attempts to fix your code.
#include <stdio.h>
#include <stdlib.h>
struct book {
char title[50];
char author[50];
int quantity;
int price;
};
struct book a;
void addbook();
//void searchbook();
//void deletebook();
void viewbook();
//void updatebook();
void returnfunc();
int main() {
int choice;
do {
printf("\n\n\t1.Add Book\n");
printf("\n\t2.Search Book\n");
printf("\n\t3.Delete Book\n");
printf("\n\t4.View Book\n");
printf("\n\t5.Update Book\n");
printf("\n\t6.Exit\n");
printf("\n\nPlease enter your choice :");
scanf("%d", &choice);
switch (choice) {
case 1 :
addbook();
break;
//case 2 :searchbook();
break;
//case 3 :deletebook();
break;
case 4 :
viewbook();
break;
//case 5 :updatebook();
break;
case 6 :
printf("THANK YOU !!");
break;
default :
printf("Wrong Choice.Please enter Again");
break;
}
}
while (choice != 6);
return 0;
}
void addbook() {
printf("\n============= PLEASE ADD NEW BOOK DETAILS ================");
int quantity;
FILE *fp;
printf("\n\nNumber of book to insert:");
scanf("%d", &quantity);
struct book a[quantity];
int i;
fp = fopen("Bibek.dat", "ab+");
for (i = 0; i < quantity; i++) {
printf("Title:");
scanf("%s", a[i].title);
printf("Author:");
scanf("%s", a[i].author);
printf("Price:");
scanf("%d", &a[i].price);
printf("\n");
}
fwrite(a, sizeof(a) , 1, fp);
fclose(fp);
printf("\n\n---NEW BOOK DETAILS WAS SUCCESFULLY ADDED---\n\n");
}
void viewbook(void) {
FILE *fp;
int i = 0, j;
//system("cls");
printf("*********************************Book List*****************************");
printf(" TITLE AUTHOR QTY PRICE\n");
j = 0;
fp = fopen("Bibek.dat", "rb");
while (fread(&a, sizeof(a), 1, fp) == 1) {
printf("%s ", a.title);
printf("%s ", a.author);
//printf("%d", a.quantity);
printf("%d ", a.price);
printf("\n\n");
j++;
i = i + a.quantity;
}
printf("Total Books =%d", j);
fclose(fp);
returnfunc();
}
void returnfunc(void) {
printf(" Press ENTER to return to main menu");
}
Test
/a.out
1.Add Book
2.Search Book
3.Delete Book
4.View Book
5.Update Book
6.Exit
Please enter your choice :1
============= PLEASE ADD NEW BOOK DETAILS ================
Number of book to insert:2
Title:foo
Author:carol
Price:2
Title:bar
Author:mallory
Price:3
---NEW BOOK DETAILS WAS SUCCESFULLY ADDED---
1.Add Book
2.Search Book
3.Delete Book
4.View Book
5.Update Book
6.Exit
Please enter your choice :4
*********************************Book List***************************** TITLE AUTHOR QTY PRICE
foo carol 2
bar mallory 3
Total Books =2 Press ENTER to return to main menu
1.Add Book
2.Search Book
3.Delete Book
4.View Book
5.Update Book
6.Exit
Please enter your choice :

Im having issues with the redefintion of "fptr"

The 15th line is what I cant fix. Please be kind enough to look at my code and diagnose the issue. I am new to programming and will appreciate anyone pointing me in the right direction.
#include <stdio.h>
#include <stdlib.h>
#define TEAMS 200
#define RUNNERS 10000
#define LENGTH 20
#define TEAMSIZE 50
FILE *fptr;
fptr = fopen("myfile.txt","w");
void getdetails();
struct person {
char name[LENGTH];
int number;
int age;
int event;
float money;
float time;
}p;
struct team {
char tname[LENGTH];
int nummembers;
float money;
struct person members[TEAMSIZE];
}t;
int main() {
int c,flag=0,i=0,j,k=0;
printf("\n---------------------------------------------------");
printf("\n---------------------------------------------------");
printf("\nHeader Specification");
while(flag==0) {
printf("\n1.Individual Registration");
printf("\n2.Team Registration");
printf("\n3.Running Events");
printf("\n4.Donation Totals");
printf("\n5.Exit");
printf("\nEnter your choice:");
scanf("%d",&c);
switch(c) {
case 1:
printf("\n For Individual Registration");
printf("\n1.Early Registration");
printf("\n2.regular Registration");
int ch;
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch) {
case 1:
printf("\n For Early Registration");
i=i+1;
getdetails(i);
break;
case 2:
printf("\n For Early Registration");
i=i+1;
getdetails(i);
break;
default:
printf("\n not valid");
break;
}
break;
case 2:
printf("\n For Team Registration");
printf("\n Enter team name:");
scanf("%s",t.tname);
printf("\n Enter team participant number:");
scanf("%d",&t.nummembers);
k=k+1;
for(j=1;j<=t.nummembers;j++) {
getdetails(k);
}
break;
case 5:
flag=1;
break;
}
}
return 0;
}
void getdetails(int i) {
printf("Enter your name:");
scanf("%s",p.name);
printf("Enter your age:");
scanf("%d",&p.age);
printf("Enter the event:");
scanf("%d",&p.event);
printf("Enter the donation amount:");
scanf("%f",&p.money);
if(fptr == NULL) {
printf("Error!");
exit(1);
}
fprintf(fptr,"\n%s register for\t%dk race\tand the number is%d.",p.name,p.event,i);
fclose(fptr);
}
A runtime-executable statement, like
fptr = fopen("myfile.txt","w");
cannot reside in global scope. It has to reside in block scope, i.e., in some function body.

Process Returned -1073741819 (0xc0000005) Code::Blocks

I'm kind of new to programming C with Code::Blocks(Version 12.11), started this semester in my college, but I manage.
I recently learned in class about pointers, memory allocation and dynamic arrays(none are my forte), and I incorporated them in my program(and it compiles)
Now the problem comes when I run the Program and go to Menu -> Add a Product, the program terminâtes when I input a price and I receive "Process Returned -1073741819 (0xc0000005)".
I did some research and found out it's an access violation but I don't really understand how to correct it.
Regards
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxCharName 64
#define maxCharUserPass 8
#define maxCharId 5
// Product Structure
typedef struct{
char name[maxCharName];
char idCode[maxCharId];
float price;
float stock;
}product;
// DataBase of Products
typedef struct{
int sizeT;
product *array;
} TProducts;
TProducts a;
// Press any Key on the Keyboard to Proceed
void pressKeyToContinue(){
puts("\n\n\n Please Press any Key to Continue...");
getchar();
}
// Start Page
void startPage(){
puts("\n\n\n -- Welcome to WeePro Manager --\n\n");
puts(" -- Version 1.0 --\n\n\n\n");
puts(" -- Developped By: Nick --");
pressKeyToContinue();
system("cls");
}
// Program Terminator
void shutdown(){
puts("\n\n\n Good-Bye");
pressKeyToContinue(); // Awaits User Input
exit(0);
}
// Asks User Information for Verification
int userLogin(){
char userName[maxCharUserPass] = "WPuser";
char inputUserName[maxCharUserPass];
char passWord[maxCharUserPass] = "12345";
char inputPassWord[maxCharUserPass];
printf("Username? ");
scanf("%s",inputUserName); fflush(stdin);
printf("Password? ");
scanf("%s", inputPassWord); fflush(stdin);
system("cls");
if((strcmp(userName, inputUserName) == 0)&&(strcmp(passWord, inputPassWord) == 0)){
return 1;
}else{ return 0;}
}
// Lists All Products With their Respective Information
void listAll(){
int idx = 0;
puts("List:");
while((idx < a.sizeT)&&(a.array[idx].name != NULL)){
printf(":::%s ( id: %s )", a.array[idx].name, a.array[idx].idCode);
printf("Price: %6.2f eur/g", a.array[idx].price);
printf("Stock: %6.2f g", a.array[idx].stock);
idx++;
}
pressKeyToContinue();
system("cls");
}
// Input Product ID Code
char* inputIdCode(){
char* tempIdCode;
puts("ID Code?");
scanf("%s", tempIdCode);
system("cls");
return tempIdCode;
}
// Search By ID Code
int searchIdCode(){
int idx = 0;
char* tempIdCode;
tempIdCode = inputIdCode();
do{
if(strcmp(a.array[idx].idCode, tempIdCode) == 0){
return idx;
}else{
idx++;
}
}while(idx < a.sizeT);
puts("No Product With Such an ID Code!");
return -1;
}
// Input Product Name
char *inputProductName(int length){
char name[maxCharName];
puts("Product Name?");
scanf("%s", name); fflush(stdin);
system("cls");
return name;
}
// Input Product Price
float inputProductPrice(int length){
float price;
puts("Product Price?");
scanf("%f", price); fflush(stdin);
system("cls");
return price;
}
// Input Product Stock
float inputProductQuantity(int length){
float quantity;
puts("Product Stock?");
scanf("%f", quantity); fflush(stdin);
system("cls");
return quantity;
}
/////////////////
// Add Product //
/////////////////
// New Product Adder
void addProduct(){
char* tempStr;
float temp;
if(a.sizeT == 0){
a.sizeT = 1;
a.array = (product*)malloc((a.sizeT)*sizeof(product));
}else{
a.sizeT++;
a.array = (product*)realloc(a.array, (a.sizeT)*sizeof(product));
}
tempStr = inputProductName(a.sizeT);
strcpy(a.array[a.sizeT].name, tempStr);
temp = inputProductPrice(a.sizeT);
temp = inputProductQuantity(a.sizeT);
system("cls");
}
void transaction(){}
////////////////////
// Delete Product //
////////////////////
// Delete Product
void deleteProduct(){
int idx, idxPro;
char* tempIdCode;
puts("Delete Which Product?\n");
tempIdCode = inputIdCode();
idxPro = searchIdCode(tempIdCode);
idx = idxPro + 1;
while(idx < a.sizeT){
a.array[idx] = a.array[idx+1];
idx++;
}
a.array = realloc(a.array, (a.sizeT-1)*sizeof(product));
}
//Product Information Modifier
void modifyProduct(){
char choice;
int tabLength;
do{
puts("Modify What?\n");
puts(" -> [N]ame\n");
puts(" -> [P]rice\n");
puts(" -> [S]tock\n\n");
puts(" -> [R]eturn to Previous Menu"); // Prints the Menus' Options
scanf("%c", &choice);
choice = toupper(choice); // Save Users' Choice And Up Case
fflush(stdin);
switch(choice){
case 'N':
system("cls");
tabLength = searchIdCode();
inputProductName(tabLength);
break;
case 'P':
system("cls");
tabLength = searchIdCode();
inputProductPrice(tabLength);
break;
case 'S':
system("cls");
tabLength = searchIdCode();
inputProductQuantity(tabLength);
break;
case 'R':
system("cls");
returnToMenu2();
break;
default:
puts("Something Went Wrong!\n");
pressKeyToContinue();
system("cls");
}
}while(choice != 'o');
}
// Sub-Menu Interface
void menu(){
char choice;
do{
puts("Please Make Your Selection.\n");
puts(" -> [A]dd a New Product\n");
puts(" -> [M]odify a Product\n");
puts(" -> [D]elete a Product\n\n");
puts(" -> [R]eturn to Main Menu"); // Prints the Menus' Options
scanf("%c", &choice); fflush(stdin);
choice = toupper(choice); // Save Users' Choice And Up Case
switch(choice){
case 'A':
system("cls");
addProduct();
break;
case 'M':
system("cls");
modifyProduct();
break;
case 'D':
system("cls");
deleteProduct();
break;
case 'R':
system("cls");
returnToMenu1();
break;
default:
puts("Something Went Wrong!\n");
pressKeyToContinue();
system("cls");
}
}while(choice != 'o');
}
// Return To Ma
> Blockquote
in Menu
void returnToMenu2(){
menu();
}
// Main Menu
void controlPanel(){
char choice;
do{
puts("Please Make Your Selection.\n");
puts(" -> [T]ransaction\n");
puts(" -> [M]enu\n");
puts(" -> [L]ist\n");
puts(" -> [S]hutdown"); // Prints the Panels' Options
scanf("%c", &choice); fflush(stdin);
choice = toupper(choice); // Save Users' Choice And Up Case
switch(choice){
case 'T':
system("cls");
transaction();
break;
case 'M':
system("cls");
menu();
break;
case 'L':
system("cls");
listAll();
break;
case 'S':
system("cls");
shutdown();
break;
default:
puts("Something Went Wrong!\n");
pressKeyToContinue();
system("cls");
}
}while(choice != 'o');
}
// Return To Main Menu
void returnToMenu1(){
controlPanel();
}
int main(){
int loginSuccess=1;
//loginSuccess = userLogin();
switch(loginSuccess){
case 0:
shutdown();
break;
case 1:
startPage();
controlPanel();
break;
}
}
An attempt is being made to write to randon memory, via the uninitialized pointer tempIdCode:
char* inputIdCode(){
char* tempIdCode;
puts("ID Code?");
scanf("%s", tempIdCode);
system("cls");
return tempIdCode;
}
You need to allocate memory for tempIdCode before attempting to write to it. You must use malloc() here (and not return the address of a local array):
char* tempIdCode = malloc(20);
if (tempIdCode)
{
/* The format specifier "%19s" instructs scanf()
to read at most 19 characters, one less than
allocated to allow for terminating null character
written by scanf(), to prevent potential buffer
overrun. */
scanf("%19s", tempIdCode);
}
The caller of the function must explicitly check for a return NULL pointer. The caller must also free() the allocated memory.
This is a killer:
// Input Product Name
char *inputProductName(int length){
char name[maxCharName];
puts("Product Name?");
scanf("%s", name); fflush(stdin);
system("cls");
return name;
}
The reference returned by this function points to an already freed block of memory on the stack, as char name is only valid as long the program is inside the function name is declared in.
When leaving the function name is freed automagically, so any dereferencing of the function's result leads to UB, as it most propably will be accessing unallocated memory.
To solve this you might like to pass in a buffer, where to read the data into:
// Input Product Name
char * inputProductName(int length, char * name){
puts("Product Name?");
scanf("%s", name); fflush(stdin);
system("cls");
return name;
}
and call it like this:
// New Product Adder
void addProduct(){
char* tempStr;
float temp;
if(a.sizeT == 0){
a.array = malloc((a.sizeT)*sizeof(product));
}else{
a.array = realloc(a.array, (a.sizeT)*sizeof(product));
}
a.sizeT++;
inputProductName(a.sizeT, a.array[a.sizeT].name);
...

Menu not working properly

#include <stdio.h>
#include <stdlib.h> //for the clear screen function
#include <string.h>
struct customer
{
int custID;
char custName[50];
char custAddress[100];
};
typedef struct customer c;
void load_menu(void);
void customers_menu(void);
void createNew(void); //initialize your file
void add_Customer(c c1[30]); //add a new record to the file
FILE *fp;
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
do
{
printf("Customer Orders Main Menu. \n\n");
printf("Please enter your choice: \n");
printf("1. Customer's Menu \n");
printf("2. Orders Menu\n");
printf("3. Product Stock Menu\n");
printf("4. Exit\n");
printf("\n");
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: system ("cls");
customers_menu();
printf("\n");
break;
case 2: system ("cls");
orders_menu();
printf("\n");
break;
case 3: system ("cls");
stock_menu();
printf("\n");
break;
case 4: printf("Quitting program!\n");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
}
void createNew(void)
{
FILE *fp;
fp=fopen("Customer.dat", "w");
if (fp==NULL)
printf("File creation failed! \n");
else
{
printf("File created! \n");
fclose(fp);
}
}
void add_Customer (c c1[30])
{
int i, n , cc=0;
FILE *fp;
fp=fopen("Customer.dat", "a");
system("cls");
if(fp==NULL)
{
printf("File Creation Failed!");
}
system("cls");
printf("Enter the number of Customers: ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("Customer's ID (numbers only) : ");
scanf("%d", &c1[i].custID);
printf("Customer's Name : ");
gets(c1[i].custName);
printf("Customer's Address : ");
gets(c1[i].custAddress);
fwrite(&c1[i], sizeof(c), 1, fp);
}cc++;
fclose(fp);
}
void recordCount(c c1[30], int *count)
{
add_Customer(c1);
count=0;
count++;
}
void customers_menu(void)
{
int choice;
c c1[30];
int i;
do
{
printf("\n");
printf("Customers Menu \n\n");
printf("Please enter your choice: \n");
printf("1. Add Customer \n");
printf("2.\n");
printf("3.\n");
printf("4. Go back to Main Menu \n");
recordCount (c1, &i);
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: add_Customer(c1);
createNew();
printf("\n");
break;
case 2:
printf("\n");
break;
case 3:
printf("\n");
break;
case 4: printf("Going back to Main Menu\n");
system ("cls");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
I have a problem since when I enter the Customers Menu it is staring to execute case 1 immediately (which still doesn't work properly). Can someone help me fix this error please because I tried everything I know and it is still in vain
I think your issue is that in customers_menu() you output the menu, but do not read the selection, instead you call recordCount() which directly calls addCustomer().
After addCustomer() we return the customers_menu() which then calls scanf() for the long gone menu.
A few other notes:
gets() is not good, I suggest you use scanf() (with %s) instead.
Doing a printf() then clearing the screen is a bit pointless.
Error messages should really go to stderr (fprintf(stderr,...)) rather than stdout (printf(...))
You code is a missing trailing }.
cc is added to, but not used.
This problem coming from if (scanf("%d",&choice)==1) because scanf will not return choice. If you enter valid answer (like number), then it returns 1 and switch case work with 1. I think that's the problem.
If you enter char instead of integer, scanf will return 0.

Resources