stack operations using switch case - c

#include <stdio.h>
#define max 20
int stk[max];
int top=-1;
void push(int);
int pop();
void peep();
void display();
int isFull();
int isEmpty();
int main()
{
int ch,item;
do
{
printf("....Stack Operations....\n");
printf("Press 1 for Push\n");
printf("Press 2 for pop\n");
printf("Press 3 for peep\n");
printf("Press 4 for display\n");
printf("Enter your choice \n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the item :- \n");
scanf("%d",&item);
push(item);
break;
case 2:
int k=pop();
printf("The poped element is %d\n",k);
break;
case 3:
peep();
break;
case 4:
display();
break;
default:
printf("Invalid Choice\n");
}
}while(ch>=1 && ch<=5);
void push(int item)
{
if(isFull())
printf("Stack Overflow\n");
else
{
top=top+1;
stk[top]=item;
}
}
int pop()
{
int s;
if(isEmpty())
printf("Stack Underflow\n");
else
{
s=stk[top];
top=top-1;
}
return s;
}
void peep()
{
if(isEmpty())
printf("Stack Underflow\n");
else
{
printf("Topmost Element of the stack is %d",stk[top]);
}
}
void display()
{
if(isEmpty())
printf("Stack Underflow\n");
else
{
for(int i=top;i>=0;i--)
printf("%d ",stk[i]);
}
}
int isFull()
{
if(top==max-1)
return 1;
else
return 0;
}
int isEmpty()
{
if(top==-1)
return 1;
else
return 0;
}
}
I wanted the program to run for all stack operations but I am getting this type of specific error:-
/usr/bin/ld: /tmp/ccHJ1ZkB.o: in function `main':
main.c:(.text+0xf7): undefined reference to `push'
/usr/bin/ld: main.c:(.text+0x103): undefined reference to `pop'
/usr/bin/ld: main.c:(.text+0x12b): undefined reference to `peep'
/usr/bin/ld: main.c:(.text+0x137): undefined reference to `display'
collect2: error: ld returned 1 exit status

It's not standard C to define functions within another function (main()) aka "nested function".
pop() returns an undefined value if the stack is empty. I changed it to return -1 but really you want to add the ability to tell caller of errors like this.
You need a block {} when introducing variables in a switch statement.
(not fixed) Avoid global variables and instead pass values to the functions that need them (functional style). Usually, you then group related data (stk and top) into a struct.
(not fixed) By convention constants, like max, should be upper case.
#include <stdio.h>
#define max 20
int stk[max];
int top=-1;
int isFull() {
return top==max-1;
}
int isEmpty() {
return top==-1;
}
void push(int item) {
if(isFull()) {
printf("Stack Overflow\n");
return;
}
stk[top++]=item;
}
int pop() {
if(isEmpty()) {
printf("Stack Underflow\n");
return -1;
}
return stk[top--];
}
void peep() {
if(isEmpty()) {
printf("Stack Underflow\n");
return;
}
printf("Topmost Element of the stack is %d",stk[top]);
}
void display() {
if(isEmpty()) {
printf("Stack Underflow\n");
return;
}
for(int i=top; i>=0; i--)
printf("%d ", stk[i]);
}
int main() {
int ch;
do {
printf(
"....Stack Operations....\n"
"Press 1 for Push\n"
"Press 2 for pop\n"
"Press 3 for peep\n"
"Press 4 for display\n"
"Enter your choice \n"
);
scanf("%d",&ch);
switch(ch) {
case 1: {
printf("Enter the item :- \n");
int item;
scanf("%d", &item);
push(item);
break;
}
case 2:
printf("The popped element is %d\n", pop());
break;
case 3:
peep();
break;
case 4:
display();
break;
default:
printf("Invalid Choice\n");
}
} while(ch>=1 && ch<=5);
}

Related

Getting "dereferencing pointer to incomplete type 'struct node' "error

I'm making a push/pop program using stacks and linked lists. Running into two errors in function pushpancake(). One is "dereferencing pointer to incomplete type 'struct node'" and the other says my "top" is undeclared. Some help would be greatly appreciated!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
int main ()
{
struct node {
int data;
struct node* next;
};
struct node* top=NULL;
int choice = 0;
printMenu ();
do
{
printf ("\nEnter a choice. ");
scanf ("%d", &choice);
switch (choice)
{
case 0:
{
exitProgram();
break;
}
case 1:
{
clrScreen();
break;
}
case 3:
{
pushpancake();
break;
}
default:
printf("\nInvalid Choice!\n");
}
}
while (choice != 0);
return 0;
}
void printMenu ()
{
printf ("0) Exit program.\n\n");
printf ("1) Clear Screen.\n\n");
printf ("2) Display the pancake stack.\n\n");
printf ("3) Push a pancake.\n\n");
printf ("4) Pop a pancake.\n\n");
}
void pushpancake()
{
char pancake[30];
int calories;
printf("Enter pancake name and its calories:");
scanf("%s %d,", pancake, &calories);
printf("The pancake has been added at the top of the stack.");
struct node *temp=(struct node*)malloc(sizeof(struct node));
strcpy(temp->pancake,pancake);
temp->data=calories;
temp->next=top;
top=temp;
}
This is my answer, hope it is useful for you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OK 1
#define ERROR 0
// infinite stack struct
typedef struct node {
int data;
struct node* next;
char name[100];
}StackNode,*LinkStackPtr;
typedef struct
{
LinkStackPtr top;
int count;
}LinkStack;
void printMenu ();
void clrScreen();
void pushpancake(LinkStack *S);
int popancake(LinkStack *S);
int PrintStackTop(LinkStack S);
int StackLength(LinkStack S);
int ClearStack(LinkStack *S);
// get length of stack
int StackLength(LinkStack S)
{
return S.count;
}
// judge stack if or not empty
int StackEmpty(LinkStack S)
{
if (S.count==0)
return OK;
else
return ERROR;
}
int look(char *strP,int c)
{
printf("%s ",strP);
printf("%d ",c);
return OK;
}
// print stack
int PrintStackTop(LinkStack S)
{
LinkStackPtr p;
p=S.top;
if(S.count == 0){
printf("stack is empty, can't print\n");
return ERROR;
}
else{
printf("The count of stack value is: %d\n",StackLength(S));
printf("\nThe value of stack is:\n");
while(p && S.count){
look(p->name,p->data);
p=p->next;
S.count--;
}
printf("\n");
return OK;
}
}
// pop a number from stack
int popancake(LinkStack *S)
{
LinkStackPtr p;
if(StackEmpty(*S))
return ERROR;
p = S->top;
S->top = S->top->next;
free(p);
S->count--;
return OK;
}
//push a number to stack
void pushpancake(LinkStack *S)
{
char pancake[100];
int calories;
printf("Enter pancake name and its calories : (format : apple 10) ");
scanf("%s %d,", pancake, &calories);
struct node *temp=(struct node*)malloc(sizeof(struct node));
strcpy(temp->name,pancake);
temp->data=calories;
temp->next=S->top;
S->top=temp;
S->count++;
printf("The pancake has been added at the top of the stack.");
}
// init stack
int InitStack(LinkStack *S)
{
S->top = (LinkStackPtr)malloc(sizeof(StackNode));
if(!S->top)
return ERROR;
S->top=NULL;
S->count=0;
return OK;
}
void clrScreen()
{
system("clear"); // may be error at windows, if yes, commment it.
}
void printMenu ()
{
printf ("0) Exit program.\n\n");
printf ("1) Clear Screen.\n\n");
printf ("2) Display the pancake stack.\n\n");
printf ("3) Push a pancake.\n\n");
printf ("4) Pop a pancake.\n\n");
}
int ClearStack(LinkStack *S)
{
LinkStackPtr p,q;
p=S->top;
while(p)
{
q=p;
p=p->next;
free(q);
}
S->count=0;
return OK;
}
int main ()
{
LinkStack s;
int choice = 0;
int booL;
printMenu ();
InitStack(&s);
do
{
printf ("\nEnter a choice. (0-4) ");
scanf ("%d", &choice);
switch (choice)
{
case 0:
{
booL = ClearStack(&s);
if(booL == OK){
printf("stack have been clear!\n");
}
PrintStackTop(s);
printf("exit the program! bye bye\n");
exit(0); // exit the program
break;
}
case 1:
{
clrScreen();
break;
}
case 2:
{
PrintStackTop(s);
break;
}
case 3:
{
pushpancake(&s);
break;
}
case 4:
{
booL = popancake(&s);
if(booL)
printf("delete top of stack by successful!");
else
printf("delete top of stack by failed!");
break;
}
default:
printf("\nInvalid Choice!\n");
break;
}
}
while (choice != 0); // if choice is 0, then exit the program
return 0;
}
this is output :
0) Exit program.
1) Clear Screen.
2) Display the pancake stack.
3) Push a pancake.
4) Pop a pancake.
Enter a choice. (0-4) 2
stack is empty, can't print
Enter a choice. (0-4) 3
Enter pancake name and its calories : (format : apple 10) aa 1
The pancake has been added at the top of the stack.
Enter a choice. (0-4) 2
The count of stack value is: 1
The value of stack is:
aa 1
Enter a choice. (0-4) 3
Enter pancake name and its calories : (format : apple 10) bb 2
The pancake has been added at the top of the stack.
Enter a choice. (0-4) 2
The count of stack value is: 2
The value of stack is:
bb 2 aa 1
Enter a choice. (0-4) 3
Enter pancake name and its calories : (format : apple 10) cc 3
The pancake has been added at the top of the stack.
Enter a choice. (0-4) 2
The count of stack value is: 3
The value of stack is:
cc 3 bb 2 aa 1
Enter a choice. (0-4) 4
delete top of stack by successful!
Enter a choice. (0-4) 2
The count of stack value is: 2
The value of stack is:
bb 2 aa 1
Enter a choice. (0-4) 0
stack have been clear!
stack is empty, can't print
exit the program! bye bye

shared memory with seamphore

i am having difficulties implementing shared memory with this code
#include<stdio.h>
#include<stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}
return 0;
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}
at the moment x is just a normal variable but if i want to fork it using a parent.c file how can i use a shared memory here so that both producer and consumer runs together
i am unable to use shared memory with this code also notable to find a good documentation online

I'm facing a runtime error in a c program that should convert from infix to postfix notation

I'm writing a program that should read equations from a txt file and fill them in a linked-list, check their validity and then convert each valid equation to post-fix notation and calculate the final result. Then write them to a file or print them on the console depends on the user choice. Following is what I've already done, I know my code is really long but I posted it all in order to make my question more clear:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node *ptr;
struct node
{
char eq[100];
char pstfix[100];
double result;
ptr next;
int topPST;
int topOP;
int validity;
};
typedef ptr list;
typedef ptr position;
list l;
void menu(); // prints the menu
void readFile(list l); //reads data from a file
int opPriority(char operators[],char operation,int top) ; // check the priority of a given operation
void isValid(position p);//Function to check the validity of each equation.
void convert(list l); // to convert from infix to postfix
void getResult(list l); // to calculate the result of an equation
double calculate(char operation, int op1,int op2);//To return the value in each step when getting the result
void showValidity(list l); // print the equations and show the ones that have errors
void acceptEq(list l); // Let the user enter equations on the console screen
void fillInfix(position p, char c[]);//A function to fill the array of infix in the node.
int isNum(char val);//returns if the value passed to it is a number or character.
void writeToFile(list l);//Write to the file
void showConsole(list l);//Show the final results on the console
int main()
{
printf("\t\t\t*Data Structure\tSecond project*\n\n\t\t\t*Convert from infix to postfix*\n\n");
menu();
l=(list)malloc(sizeof(struct node));
return 0;
}
//Function to print the menu and let the program work depending on the choice.
void menu()
{
system("cls");
int choice;
printf("\t\t\t\tMenu\n\n\t\t\t1.Read equations from file.\n\t\t\t2.Check validity.\n\t\t\t3.Convert to postfix.\n\t\t\t4.Add more equations to the file.\n\t\t\t\n\t\t\t5.Calculate Results.\n\t\t\t6.Write results to file.\n\t\t\t7.Show results on the console.\n\t\t\t8.End.\n\n\t\t\tEnter Your choice number please\n\t\t\t");
scanf("%d",&choice);
switch (choice)
{
case 1: readFile(l);
break;
case 2: isValid(l);
break;
case 3: convert(l);
break;
case 4: acceptEq(l);
break;
case 5: getResult(l);
break;
case 6: writeToFile(l);
break;
case 7: showConsole(l);
break;
case 8: exit(0);
}
}
//The following function should read equations from a file specified by the user
void readFile(list l)
{
system("cls");
char fileName[50];
FILE *eqFile;
printf("\t\t\tEnter the title of the file please\n\t\t\t");
scanf("\t\t\t%s",fileName);
eqFile=fopen(fileName,"r");
//To ensure the existence of the requested file.
while (eqFile == NULL)
{
printf("\t\t\tThe file you asked for does not exist. Enter another name or enter 'back' to return to menu\n\t\t\t");
scanf("\t\t\t%s",fileName);
if(strcmp(fileName,"back")==0) menu();
else eqFile=fopen(fileName,"r");
}
(l)->next=(position)malloc(sizeof (struct node));
position temp=(l)->next;
char line[100];
while (temp != NULL){
while (fgets(line,sizeof line, eqFile) != NULL)
{
isValid(temp);
if ((temp)->validity) fillInfix(temp,line);
temp=(temp)->next;
(temp)->next=NULL;
}
}
fclose(eqFile);
int choice;
printf("\t\t\tData Read Successfully\n\t\t\tEnter 0 to exit or 1 to return to menu\n\t\t\t");
scanf("%d",&choice);
if (choice) menu();
else exit(0);
}
void isValid(list l)
{
system("cls");
position temp;
temp=l;
int i,count=0;
while((temp)->next!=NULL)
{
for (i=0;i<100;i++)
{
if (((l)->eq[i]=='+' && (l)->eq[i+1]=='*') || ((l)->eq[i]=='-' && (l)->eq[i+1]=='*')|| ((l)->eq[i]=='*' && (l)->eq[i+1]=='/') || ((l)->eq[i]=='/' && (l)->eq[i+1]=='+')|| ((l)->eq[i]=='/' && (l)->eq[i+1]=='-') || (l)->eq[i]==' ')
count++;
}
if (count!=0) (temp)->validity=0;
temp=(temp)->next;
}
int choice;
printf("\t\t\tChecking validity is done enter 0 to quite or 1 to return to menu\n\t\t\t");
scanf("%d",&choice);
if(choice) menu();
else exit(0);
}
void fillInfix(position p, char line[])
{
int i;
for (i=0;i<100;i++)
{
while (line[i]!='\0')
{
(p)->eq[i]=line[i];
}
}
}
void push(char st[],char element, int top)
{
++top;
st[top]=element;
}
char pop(char st[],int top)
{
char elemnt=st[top];
--top;
return elemnt;
}
int opPriority(char operators[], char operation, int top)
{
if ((operation=='*' && operators[top]=='-') || (operation=='*' && operators[top]=='+') || (operation=='*' && operators[top]=='/') || (operation=='/' && operators[top]=='-')|| (operation=='/' && operators[top]=='+') || (operation=='+' && operators[top]=='-')) return 0;
else
if ((operation=='(' && operators[top]=='*') || (operation=='(' && operators[top]=='/') || (operation=='(' && operators[top]=='+') || (operation=='(' && operators[top]=='-')) return 0;
else if (operation==')') return 2;
else
return 1;
}
int isNum(char val)
{
if (val!='+' && val!='-' && val!='*' && val!='/') return 1;
else return 0;
}
void convert(list l)
{
position temp=l;
int i;
char operators[100];
while ((temp)->next != NULL)
{
temp=(temp)->next;
if ((temp)->validity)
{
for (i=0;i<100;i++)
{
if (isNum((temp)->eq[i])) push((temp)->pstfix,(temp)->eq[i],(temp)->topPST);
else
{
int priority=opPriority(operators,(temp)->eq[i],(temp)->topOP);
if (priority==1)
{
push((temp)->pstfix,pop(operators,(temp)->topOP),(temp)->topPST);
push(operators,(temp)->eq[i],(temp)->topOP);
}
else
if (priority ==0) push(operators,(temp)->eq[i],(temp)->topOP);
else
if (priority==2)
{
while (operators[(temp)->topOP]!='(')
{
push((temp)->pstfix,pop(operators,(temp)->topOP),(temp)->topPST);
}
char trash=pop(operators,(temp)->topOP);//Unwanted closed bracket
}
}
}
}
}
int choice;
printf("\t\t\tConversion Done successfully. Enter 0 to quite or 1 to return to menu\n\t\t\t");
scanf("%d",&choice);
if(choice) menu();
else exit(0);
}
void acceptEq(list l)
{
system("cls");
char newEq[100];
printf("\t\t\t Enter your equation please. Note that your equation must not exceed the 100 characters length.\n\t\t\t");
scanf("\t\t\t%s",newEq);
position temp=l;
position p=(position)malloc(sizeof (struct node));
while ((temp)->next!=NULL)
{
temp=(temp)->next;
}
(temp)->next=p;
isValid(p);
if ((p)->validity)
{
fillInfix(p,newEq);
convert(p);
}
}
void getResult(list l)
{
system("cls");
position temp=l;
while ((temp)->next != NULL)
{
temp=(temp)->next;
int i=0;
while ((temp)->pstfix[i]!= '\0')
{
if ((temp)->pstfix[i]=='+' || (temp)->pstfix[i]=='-' || (temp)->pstfix[i]=='*' || (temp)->pstfix[i]=='/')
(temp)->result = calculate((temp)->pstfix[i],(temp)->pstfix[i-2],(temp)->pstfix[i-1]);
push((temp)->pstfix,(temp)->result,(temp)->topPST);
printf("\n\t\t\t%c",(temp)->pstfix[i]);
i++;
}
printf("=%f",(temp)->result);
}
}
double calculate (char operation,int op1,int op2)
{
double result;
if (operation=='+') result=op1+op2;
if (operation=='-') result=op1-op2;
if (operation=='*') result=op1*op2;
if (operation=='/') result=op1/op2;
return result;
}
void writeToFile(list l)
{
system("cls");
char fileWName[50];
printf("\n\t\t\tEnter the name of the file you want to print on please\n\t\t\t");
scanf("\t\t\t%s",fileWName);
FILE* resultFile;
resultFile=fopen(fileWName,"w");
position temp=l;
fprintf(resultFile,"Infix Notation:\t\t");
fprintf(resultFile,"Validity:\t\t");
fprintf(resultFile,"Postfix Notation:\t\t");
fprintf(resultFile,"Value:\t\t\n");
while ((temp)->next != NULL)
{
temp=(temp)->next;
int i=0;
while ((temp)->eq[i]!='/0')
{
fprintf(resultFile,"%c",(temp)->eq[i]);
i++;
}
fprintf(resultFile,"\t\t");
i=0;
while ((temp)->pstfix[i]!='/0')
{
fprintf(resultFile,"%c",(temp)->pstfix[i]);
i++;
}
fprintf(resultFile,"\t\t");
if ((temp)->validity == 0) fprintf(resultFile,"INVALID");
else
{
fprintf(resultFile,"VALID\t\t");
fprintf(resultFile,"%f",(temp)->result);
}
}
fclose(resultFile);
int choice;
printf("\t\t\tDATA WRITTEN TO FILE SUCCESSFULLY. Press 1 to return to menu or 0 to quite\n\t\t\t");
scanf("%d",&choice);
if (choice) menu(l);
else exit(0);
}
void showConsole(list l)
{
system("cls");
position temp=l;
printf("Infix Notation:\t\t");
printf("Validity:\t\t");
printf("Postfix Notation:\t\t");
printf("Value:\t\t\n");
while ((temp)->next != NULL)
{
temp=(temp)->next;
int i=0;
while ((temp)->eq[i]!='/0')
{
printf("%c",(temp)->eq[i]);
i++;
}
printf("\t\t");
i=0;
while ((temp)->pstfix[i]!='/0')
{
printf("%c",(temp)->pstfix[i]);
i++;
}
printf("\t\t");
if ((temp)->validity == 0) printf("INVALID");
else
{
printf("VALID\t\t");
printf("%f",(temp)->result);
}
}
int choice;
printf("\t\t\tDATA WRITTEN SUCCESSFULLY. Press 1 to return to menu or 0 to quite\n\t\t\t");
scanf("%d",&choice);
if (choice) menu();
else exit(0);
}
I've already used debugger to find out where my problem is. And now I know that there's a compiling error in this statement:
(l)->next=(position)malloc(sizeof (struct node));
I'm wondering what's wrong with this statement? I'm trying to allocate space for a node in order to be able to create more nodes for each line (equation).
In this case it's easy to see what's wrong: You try to dereference a NULL pointer.
To understand why, you should know that all global variables, like the variable l in your program, are zero-initialized. That basically means that the pointer l is initialized to NULL.
The problem arise because memory for l is not allocated until after you call the menu function. So any function called from menu will have l equal NULL.
There are a few other problems with your code. One is that memory you allocate with malloc is not initialized at all, so for example when you later in the readFile function call isValid with the newly allocated node, and in isValid dereference the temp->next pointer, the value of that next pointer is indeterminate (and in reality will be seemingly random). Accessing uninitialized data like that will lead to undefined behavior. This of course goes for all data inside the structure, not just pointers.
You also don't seem to set temp->validity to non-zero anywhere.

Reading a text file to a doubly linked list

I'm coding a contact manager using a doubly linked list that is manipulated by functions using pointers that reads in a contactList.txt.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
#include<stdlib.h>
#include<dos.h>
//functions
listelement * getFirst(listelement *listpointer,string query[MAX]);
void getLast();
void getEmail();
void getCompany();
void getNumber();
void editCon();
void delCon();
void addCon();
void listAll();
void sortCon();
void Menu (int *choice);
#define MAX 20
//struct to order contactList
struct contact
{
string firstName[MAX],lastName[MAX],email[MAX],companyName[MAX];
long phoneNum[MAX];
struct listelement *link
struct contact *next;
struct contact *prev;
}list;
int main()
{
listelement listmember, *listpointer;
string query;int iChoice = 0;
listpointer = NULL;
Menu (&iChoice);
int iChoice;
fflush(stdin);
scanf_s("%d", &iChoice);
// user enters one of 9 values
// options are as follows: get first name,last name,list all contacts,search through contacts,add a new contact,edit/delete or sort contacts.
switch(iChoice)
{
case 1:
{
printf ("Enter contact first name to get details ");
scanf ("%d", &query);
listpointer = getFirst (listpointer, query);
break;
}
case 2:
{
getLast();
break;
}
case 3:
{
listAll();
break;
}
case 4:
{
getEmail();
break;
}
case 5:
{
getCompany();
break;
}
case 6:
{
getNumber();
break;
}
case 7:
{
addCon();
break;
}
case 8:
{
editCon();
break;
}
case 9:
{
delCon();
break;
}
case 10:
{
sortCon();
break;
}
case 11: // exit
{
printf("\n\nProgram exiting!...");
exit(0);//terminates program
break;
}
default:
printf ("Invalid menu choice - try again\n");
break;
}//end of switch
return(iChoice);
}//end of main
//menu function to test if invalid input was entered in a menu choice.
void Menu (int *iChoice)
{
char local;
system("cls");
printf("\n\n\t\\n\n");
printf("\n\n\t\tWelcome to my Contact Manager\n\n");
printf("\n\t\t1. First name");
printf("\n\t\t2. Last name");
printf("\n\t\t3. List all contacts");
printf("\n\t\t4. Search email");
printf("\n\t\t5. Search company name");
printf("\n\t\t6. Search number");
printf("\n\t\t7. Add contact");
printf("\n\t\t8. Edit contact");
printf("\n\t\t9. Delete contact");
printf("\n\t\t10. Sort contacts");
printf("\n\t\t11. Exit");
printf("\n\n\t\tEnter your menu choice: ");
do
{
local = getchar ();
if ( (isdigit(local) == FALSE) && (local != '\n') )
{
printf ("\nYou must enter an integer.\n");
printf ("");
}
} while (isdigit ((unsigned char) local) == FALSE);
*iChoice = (int) local - '0';
}
//function to get a contact by entering first name
listelement * getFirst (listelement *listpointer, string query)
{
//variables
char query[MAX],firstName[MAX];
FILE *fp, *ft;
int i,n,ch,l,found;
system("cls");
do
{
found=0;
l=strlen(query);
fp=fopen("ContactList.txt","r");
system("cls");
printf("\n\n..::Search result for '%s' \n===================================================\n",query);
while(fread(&list,sizeof(list),1,fp)==1)
{
for(i=0;i<=l;i++)
firstName[i]=list.firstName[i];
firstName[l]='\0';
if(stricmp(firstName,query)==0)
{
printf("\n..::First Name\t: %s\n..::Second Name\t: %ld\n..::Email\t: %s\n..::CompanyName\t: %s\n..::Number\t: %s\n",list.firstName,list.lastName,list.email,list.companyName.list.phoneNumber);
found++;
if (found%4==0)
{
printf("..::Press any key to continue...");
getch();
}
}
}
if(found==0)
printf("\n..::No match found!");
else
printf("\n..::%d match(s) found!",found);
fclose(fp);
printf("\n ..::Try again?\n\n\t[1] Yes\t\t[11] No\n\t");
scanf("%d",&ch);
}while(ch==1);
}
Anyone have any idea as to where I'm going wrong in the code?Thanks
Your errors are because:
1) you don't define listelement anywhere
2) you don't define string anywhere (and it's not a type in C)
3) You need to move the #define MAX up above before you use it.
4) You don't define FALSE anywhere (and it's not a type in C)
5) You're redefining elements too, in getFirst() you've passed in query as a "string", then you
define a new query as a char array
6) You get redefinition errors because you've got more than one define. That's somewhat #5 but there's more as well. In your main you declare iChoice here: string query;int iChoice = 0;
then you declare it again int iChoice; right after your Menu() call
7) Please don't do fflush(stdin) that's undefined behavior as per the C standard

C stack array problem

My function code for peek is not working? why is that? can anyone help me with my peek function?
#include<stdio.h>
#include<stdlib.h>
#define maxsize 10
int stack[maxsize];
int stacktop=0;
void instructions();
int process();
int push(int value);
int pop();
void display();
void peek();
int main()
{
process();
getch();
}
int process()
{
int val;
int choice;
do
{
instructions();
printf("Enter Your Choice: ");
scanf("%d",&choice);
switch( choice )
{
case 1:
printf("\nElement to be Pushed : ");
scanf("%d",&val);
push(val);
break;
case 2:
val=pop();
if(val!=-1)
{
printf("Popped Element : %d\n",val);
}
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
break;
}
}while(choice !=5);
}
void instructions()
{
printf("Enter Your choice for the following process\n");
printf("\n[1]Push a Node on top of the list");
printf("\n[2]Pop a node off the list");
printf("\n[3]Peek The Top Node");
printf("\n[4]Display The Whole list");
printf("\n[5]Exit The Program\n");
}
int push(int val)
{
if(stacktop<maxsize)
{
stack[stacktop++]=val;
}
else
{
printf("Stack is full");
}
}
int pop()
{
int a;
if(stacktop>0)
{
a=stack[--stacktop];
return a;
}
}
void display()
{
int i;
i = 0;
if(stacktop>0)
{
printf("Elements are:");
while(i<stacktop)
{
printf("\n%d--\n",stack[i++]);
}
}
}
void peek()
{
printf("%d",stacktop);
}
Is it supposed to be:
printf("%d\n", stack[stacktop - 1]);
Print the contents, rather than the size of the stack?
Obviously you'd also need to bounds check to make sure you're not printing outside of the range of your stack (when it's empty)
I know this isn't Code Review, but I thought I would give you a few bits of advice.
When you call scanf, always check the result. For example, if the user enters something other than a decimal number, your code will end up putting an indeterminate value into the choice or val variables. The scanf function returns the number of items that were successfully read. If you asked for one item, and scanf returns 1, then you can rely on the value of that object:
int choice;
if (scanf("%d", &choice) != 1)
// handle error, can't rely on value of "choice"
else
// continue onwards, can rely on value of "choice"
Usually, the \n escapes go at the end of the string literal, not at the beginning. It is more common to do it this way, but it doesn't mean it should always go at the end.
printf("Enter Your choice for the following process\n\n");
printf("[1]Push a Node on top of the list\n");
printf("[2]Pop a node off the list\n");
printf("[3]Peek The Top Node\n");
For outputting simple strings, consider just using the puts function, which automatically appends the new-line character for you:
puts("Enter Your choice for the following process");
puts("");
puts("[1]Push a Node on top of the list");
puts("[2]Pop a node off the list");
puts("[3]Peek The Top Node");
Your display method is a perfect example of when to use a for loop instead of a while loop. Generally speaking, use a for loop when you know exactly how many items you have and you want to iterate over each of them:
void display()
{
int i;
puts("Elements are:");
for (i = 0; i < stacktop; i++)
printf("\n%d--\n", stack[i]);
}
To reverse the order of the stack, simply start at the top and go backwards:
void display()
{
int i;
puts("Elements are:");
for (i = stacktop - 1; i >= 0; i--)
printf("\n%d--\n", stack[i]);
}

Resources