I was given this problem as a lab assignment and I've only got 3 days left to submit it.
The program is to print 1 for a palindrome and -1 for not palindrome. I could've easily done this using strrev() but the coding platform that our college uses is hosted on Linux so most built in string functions don't work.
I've tried many work arounds and nothing is working. I'm forced to implement the problem without string functions so it's getting a bit complicated. I managed to find some decent semi working code but it fails at some test cases.
Apparently, it's printing the opposite sign of -1 or 1 in some test cases and that's whats causing the errors.
#include<stdio.h>
#include<string.h>
int main(){
char string[25],reverse_string[25]={'\0'};
int i, length = 0, flag =0;
int i,length=0,t,flag=0;
scanf("%d",&t);
while(t--){
gets(string);
for(i=0;string[i]!='\0';i++){
length++;
}
for(i=length-1;i>=0;i--){
reverse_string[length-i-1]=string[i];
}
for(flag=1,i=0;i<length;i++){
if(reverse_string[i]!=string[i]){
flag=0;
}
}
if(flag==1){
printf("1\n");
}
else{
printf("-1\n");
}
}
}
Expected output:
3
asdffgg
-1
qq
1
dfghht
-1
The output that I'm getting in the website:
3
asdffgg
1
qq
-1
dfghht
-1
The output that I'm getting locally in the console:
3
1
asdffgg
-1
qq
-1
For starters the code shall not be compiled becuase there are duplicated declarations
You should remove the first declaration.
Now about your obtained output if your actual code does not contain the above mentioned typo.
After this call of
scanfthe input buffer will contain the new line character
'\n'that corresponds to the pressed keyEnter. So the following call ofgetsat once encounters the new line character and as a result stores an empty string. And you get the following outputbecause an empty string is a palindrome. Pay attention to that the function
getsremoves the new line chracter'\n'from the input buffer.Then after you entered this string
Your program correctly reported that the string is not a palindrome.
After that you entered the string
but within the current iteration of the while loop you did not reset the value of the variable
length. It still stores the length of the previous entered string"asdffgg"that is equal to7. And this for loop for the string"qq"makes the value of the variable
lengthequal to9(7plus the length of the string"qq").As a result the following for loops invoke undefined behavior and you get
First of all do not use the function
gets. It is unsafe and is not supported by the C Standard. Instead use eitherscanforfgets. For exampleThe auxiliary array
reverse_stringis redundant. And within each iteration of the while loop reset the value of the variablelengthto0.Also you should declare variables in minimum scopes where they are used. So before the while loop declare only the variable
tAll other variables including the array
stringdeclare within the while loop.For example to check if a string is a palindrome you can write