Declaring Int variables causes segmentation fault? - c

Hey guys I'm having a really peculiar segmentation fault coming up in my program. This program is suppose to automate the card game "war" and so far I've been able to build two randomized half decks for both players. Which would appear to show that enqueue is working correct. I was also able to dequeue all the values and they appeared in the correct order. However inside main if I uncomment the integer declarations in main the program segfaults every time. I can not for the life of me figure out how simple declarations could cause faults. Please note this is my only second assignment for using queues.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef struct node
{
int value;
int suit;
char*sname;
char*txt;
struct node *next;
} node;
int isempty(node *base){
if (base==NULL)
{return 1;}
else
return 0;
}
void printlist(node *base){
node *current=base;
if(base==NULL)
{
printf("The List is empty!\n");
return;
}
else
{
printf("Content: \n");
int count=0;
while(current!=NULL){
count++;
printf("%s \tof \t%s\n",current->txt,current->sname);
current=current->next;
}
printf("\nCount:%d\n",count);
}
}
char* valname(int n){
char *name;
switch(n)
{
case 0:name="two";break;
case 1:name="three";break;
case 2:name="four";break;
case 3:name="five";break;
case 4:name="six";break;
case 5:name="seven";break;
case 6:name="eight";break;
case 7:name="nine";break;
case 8:name="ten";break;
case 9:name="Jack";break;
case 10:name="Queen";break;
case 11:name="King";break;
case 12:name="Ace";break;
default:printf("Broken\n");exit(1);
}
return(name);
}
char* suitname(int n){
char *name;
switch(n){
case 0:name="Hearts";break;
case 1:name="Spades";break;
case 2:name="Clubs";break;
case 3:name="Diamonds";break;
default:printf("Broken\n");exit(1);
}
return(name);
}
void enqueue(node **base,int item){
node *nn,*current=*base;
nn=malloc(sizeof(node));
if(*base==NULL)
{
*base=nn;
}
else
{
while(current->next!=NULL){
current=current->next;
}
current->next=nn;
}
nn->value=item;
nn->txt=valname(item%13);
nn->sname=suitname(item/13);
nn->next=NULL;
}
int dequeue(node **base){
node *current=*base,*temp;
if (isempty(*base)==0){
int giveback=current->value;
if(current->next==NULL)
{
free(*base);
*base=NULL;
}
else
{
temp=current->next;
free(current);
*base=temp;
}
return giveback;
}else{return -1;}
}
void createdecks(node **deck1,node **deck2){
int i=0;
int thenumber=0;
int deck[52]={0};
for(i=0;i<26;i++){
thenumber=rand()%52;
if(deck[thenumber]==0){
//add to list
enqueue(deck1,thenumber);
deck[thenumber]=1;
}
else
{
i--;
}
}
for(i=0;i<26;i++){
thenumber=rand()%52;
if(deck[thenumber]==0){
//add to list
enqueue(deck2,thenumber);
deck[thenumber]=1;
}
else
{
i--;
}
}
}
int main(void){
node *d1,*d2,*warholder;
//int c1=0,c2=0; //THIS LINE!!!!!!!!!!!
srand(time(NULL));
createdecks(&d1,&d2);
//printlist(d1);
//printlist(d2);
int i=0;
for(i=0;i<26;i++)
printf("%d ",dequeue(&d1)); //return testing
printf("\n");
printlist(d1);
}
Professor's example function
char * namenum( int num)
{
char * name;
switch(num)
{
case 0:
name = "zero"; break;
case 1:
name = "one"; break;
case 2:
name = "two"; break;
case 3:
name = "three"; break;
case 4:
name = "four"; break;
case 5:
name = "five"; break;
case 6:
name = "six"; break;
case 7:
name = "seven"; break;
case 8:
name = "eight"; break;
case 9:
name = "nine"; break;
default:
printf("Invalid Number generated\n");
exit(1);
}
return name;
}

I briefly looked at the code, and it looks to me like you have an uninitialized-variable problem. You declare this in main():
node *d1,*d2,*warholder;
And then you pass it to createdecks(), which in turn calls enqueue(). enqueue() assumes that the pointers are initialized.
Try to initialize d1 and d2 in main():
node *d1,*d2,*warholder;
d1 = d2 = warholder = NULL;

Its not due to declaring int. You have not allocated memory to char *name on several times before using it. for example
char* valname(int n){
char *name;
allocate memory using malloc() before using name after above code
char* suitname(int n){
char *name;
same mistake again
If you want to avoid such situation use array instead of pointer

Related

Refactoring: Very similar switch cases

I have several struct declared which contain different data. I also have an enum that corresponds to those structures. There are several places in my code where I need to access information about the structures and I'm doing it via the enum. This results in few switch statements that return this information.
I've enclosed those switch statements in their own functions in order to re-use wherever possible. This resulted in three functions that look very similar.
Example psuedo-code:
#include <stdio.h>
typedef struct
{
int varA;
char varB;
} A;
typedef struct
{
int varA;
int varB;
int varC;
} B;
typedef struct
{
int varA;
short varB;
} C;
typedef enum { structA, structB, structC } STRUCT_ENUM;
int returnSize(STRUCT_ENUM structType)
{
int retVal = 0;
switch(structType)
{
case structA:
retVal = sizeof(A);
break;
case structB:
retVal = sizeof(B);
break;
case structC:
retVal = sizeof(C);
break;
default:
break;
}
return retVal;
}
void printStructName(STRUCT_ENUM structType)
{
switch(structType)
{
case structA:
printf("Struct: A\r\n");
break;
case structB:
printf("Struct: B\r\n");
break;
case structC:
printf("Struct: C\r\n");
break;
default:
break;
}
}
void createDataString(STRUCT_ENUM structType, char* output, unsigned char* input)
{
switch(structType)
{
case structA:
{
A a = *(A*)input;
sprintf(output, "data: %d, %d", a.varA, a.varB);
break;
}
case structB:
{
B b = *(B*)input;
sprintf(output, "data: %d, %d, %d", b.varA, b.varB, b.varC);
break;
}
case structC:
{
C c = *(C*)input;
sprintf(output, "data: %d, %d", c.varA, c.varB);
break;
}
default:
break;
}
}
int main(void) {
char foobar[50];
printf("Return size: %d\r\n", returnSize(structA));
printStructName(structB);
C c = { 10, 20 };
createDataString(structC, foobar, (unsigned char*) &c);
printf("Data string: %s\r\n", foobar);
return 0;
}
Those free functions basically contain the same switch with different code placed in the cases. With this setup, adding new struct and enum value results in three places in the code that needs changing.
The question is: is there a way to refactor this into something more maintainable? Additional constraint is that the code is written in C.
EDIT: online example: http://ideone.com/xhXmXu
You can always use static arrays and use STRUCT_ENUM as the index. Given the nature of your functions, I don't really know if you would consider it more maintainable, but it's an alternative I usually prefer, examples for names and sizes:
typedef enum { structA, structB, structC, STRUCT_ENUM_MAX } STRUCT_ENUM;
char *struct_name[STRUCT_ENUM_MAX] = {[structA] = "Struct A", [structB] = "Struct B", [structC] = "Struct C"};
size_t struct_size[STRUCT_ENUM_MAX] = {[structA] = sizeof(A), [structB] = sizeof(B), [structC] = sizeof(C)};
for printing content you can keep a similar array of functions receiving a void * that will print the value of this argument.
Edit:
Added designated initializers as per Jen Gustedt's comment.
You can make it into a single function and a single switch, with an additional parameter. Like so
int enumInfo(STRUCT_ENUM structType, int type) // 1 = returnSize 2 = printStructName
{
int retVal = 0;
switch(structType)
{
case structA:
If ( type == 1 ) { retVal = sizeof(A); }
else { printf("Struct: A"); }
break;
case structB:
If ( type == 1 ) { retVal = sizeof(B); }
else { printf("Struct: B"); }
break;
case structC:
If ( type == 1 ) { retVal = sizeof(C); }
else { printf("Struct: C"); }
break;
default:
break;
}
return retVal;
}

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.

c doubly-linked list display method showing redundant elements

I have a small doubly-linked list application. I want to add elements inside the list and then display the list normally. At the output i get my inserted elements allright, but after them i get a bunch of strange numbers( such as .... 28482 -20048 2817 ...... )
I believe it's a problem of space allocation.
Any help is appreciated, thanks in advance!
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <stdlib.h>
typedef struct elem {
int number;
struct elem * urm;
struct elem * prec;
}nod;
nod *prim=NULL,*ultim=NULL, *local=NULL, *p=NULL;
void insert_element(int numb){
nod *local=(nod *)malloc(sizeof(nod));
local->number = numb;
if (prim==NULL){
prim=local;
ultim=local;
}
else{
ultim->urm = local;
local->prec = ultim;
ultim=local;
}
}
void load_data()
{
int i,n;
nod *c = (nod *)malloc(sizeof(nod));
printf("\n cate elemente va avea lista?");
scanf("%d", &n);
printf("avem %d elemente", n);
for(i=1;i<=n;i++){
printf("\n number: ");
scanf("%d", &c->number);
insert_element(c->number);
}
}
void list_left_to_right()
{
nod *p = (nod*) malloc(sizeof(nod));
p=prim;
while(p){
printf("%d ", p->number);
p=p->urm;
}
printf("\n");
}
int main()
{
int op;
do{
printf("\n1.Enter some data\n");
printf("2.Display left - > right the data\n");
printf("0.Exit\n");
printf("choice : ");
scanf("%d",&op);
switch(op){
case 1: load_data(); break;
case 2: list_left_to_right(); break;
case 0: break;}
}
while (op!=0);
return 0;
}
(1) You have a memory leak in list_left_to_right():
nod *p = (nod*) malloc(sizeof(nod));
p=prim;
This leaks the block returned by malloc().
(2)
void insert_element(int numb) {
nod *local=(nod *)malloc(sizeof(nod));
local->number = numb;
// TODO: set local->urm and local->prec to NULL
if (prim==NULL) {
prim=local;
ultim=local;
OK, so the first time insert_element() is called, the new element is both the head and the tail.
Bug: You need to set the urm and prec fields to NULL. They have undefined values initially.
}
else {
ultim->urm = local;
local->prec = ultim;
ultim=local;
}
}
After that, the subsequent elements are inserted as a new tail (ultim).
Bug: But again you need to make sure that local->urm is set to NULL.

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