[Courses] [C] What is wrong here??

Peter Clay pete at flatline.org.uk
Tue Aug 13 18:45:51 EST 2002

On Tue, 13 Aug 2002, Anand R wrote:

> My purpose is to accept a string input from the user, and check whether it
> is a palindrome or not. I tried hard to figure out how to write a C function
> to reverse a string, and how to store this reversed value in another string.
> If somebody could tell me where I am going wrong here. Any pointers to
> understand this better would be greatly appreciated. 

OK. Laura has already suggested that you draw what memory looks like -
I'll second that as it's the only way to really understand what's going

I also reccomend thinking "there is no such thing as a string in
C". Because they're not first-class data types, things like returning
strings and passing them as arguments are fraught with possible problems.

> #include<stdio.h>
> #include<string.h>
> #include<stdlib.h>
> char strrev(char array[]);
> int main()
> {
>         char string1[10];

Add a "char temp[10];" as well. It's a good idea to #define STRINGSIZE 10
as well, it helps if you want to change it later.

>         fflush(stderr);
>         fprintf(stderr,"\nEnter a string: ");
>         fflush(stderr);
>         fflush(stdin);
>         fgets(string1,sizeof(string1),stdin);
Good to see you're avoiding buffer overruns here :)

At this point I would:
 temp[STRINGSIZE-1]=0; /* Ensure null termination */

>         printf("\nThe reversed string is: %s\n",temp);
>         if(strcmp(temp,strrev(string1))==0)
>         {
>         printf("\nPalindrome\n");
>         }
>         else
>         {
>         printf("\nSorry\n");
>         }*/

.. and then I would write a strrev that reversed a string in-place, by
taking a pointer to the start and a pointer to the end, then move the
pointers in swapping values along the way.

Reversing a string in-place means that you don't have to do any memory
allocation in strrev(). However, if you do this then you have to take a
copy of the original string or you can't compare it against anything

Peter Clay                                         | Campaign for   _  _| .__
                                                   | Digital       /  / | |
                                                   | Rights!       \_ \_| |
                                                   | http://uk.eurorights.org

More information about the Courses mailing list