Our professor required us to check if a word is a palindrome by using stacks.
Every time I run it, there’s an error: Unhandled Exception. Access violation What am I doing wrong? How can i improve my code? My code is as follows:
typedef struct stack{
char name;
struct stack * next;
}Stack;
void push(Stack**head, char value);
char pop(Stack**head);
int main(){
char word[11];
int i=0;
int lenght = 0;
Stack*head = NULL;
printf("Please type the word: ");
scanf("%s", word);
lenght = strlen(word);
while(word[i]!='\0'){
push(&head, word[i]);
i++;
}
i = 0;
while(pop(&head)==word[i]){
i++;
}
if(i==lenght) printf("The word is a palindrome");
else printf("The word is not a palindrome");
}
Your
pushfunction should takeSo the method signature becomes:
and in the body of the function you add
valueto the top of stack as:Also you must always check the return value of
malloc.Since you are returning the popped value from the function
popit’s return type must not bevoid, change it tocharin both the declaration and the definition as:There is another logical error:
To start with you push all the characters of the input into the stack. Next you start popping the characters. There is no terminating condition for your popping. When you’ve popped all the characters (so your stack is empty) the next call to
popwill lead to a crash as you’ll be dereferencing aNULLpointer (*headwill beNULL).To fix this you pop only the characters you’ve pushed by doing:
Since the
&&is short circuited,popwill not be called once you’ve popped all the characters.Alternatively (and preferred approach) is to write another function called
isEmptywhich returntrue/1when the stack is empty and use this method before you call thepopmethod.