Palindrome checking through Pointers

Don't know WTF is happening but the code is showing - "Yes it is a palindrome", even if it is not. Please heeeeeeelp. Preferring direct answers. URGENT.

General Information: I'm in Class XII, using Turbo C++ v3.0 Borland

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void palin(char *p)
{
	char *a=p,*b=strrev(p);
	if(0==strcmpi(b,a))
	{
		cout<<"\n\n\tYes, it is a palindrome";
	}
	else
	{
		cout<<"\n\n\tNo, it is not a palindrome";
	}
}
void main()
{
	clrscr();
	char *ch[20],i,j;
	cout<<"\n\tEnter String: ";
	gets(*ch);
	palin(*ch);
	getch();
}
strrev() reverses the original string.
When comparing a and b, both point to that same (now reversed) string.
What you need to do is to allocate a separate array, and use strcpy() to make a copy of the original string, then reverse that copy only.

Also, main is misusing the character array by declaring an array of pointers, instead of just an array of characters.
 
char *ch[20]
should be
 
char ch[20]
Last edited on
You can allocate and copy the string with strdup()
Don't forget to free the allocated string.
Of course a more direct approach would be to not make a copy, and not reverse the string. Instead, use two pointers, set one to point to the start, the other to the end of the string. Then compare character by character until either there is a difference, or the two pointers meet in the middle. Might be an interesting challenge to have a go at that.
Topic archived. No new replies allowed.