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

Kathryn Hogg kjh at flyballdogs.com
Tue Aug 13 10:06:26 EST 2002

>>char strrev(char array[])
>>        register int i;
>>        for(i=strlen(array)-1;i>=0;i--)
>>        {
>>                return *array;
> I'm mildly suprised this compiles without warnings because you say you
> return  a char, but you're returning a pointer to an array.

return *array;  is for all intents and purposes the same as

return array[0];

I would expect that an error in the call to strcmp since it's prototype
should be "int strcmp(const char *, const char *)" and the call to strrev()
is returning a character.

What is probably needed is for strrev to return a "char *" that is allocated
on the heap with malloc:

char *strrev(const char *s)
     char *r = 0;

     if (s == 0) {
         return 0;

      r = (char *) malloc(strlen(s) + 1);

      /*now copy the input string s to r but backwards */

      return r;

Don't forget to call free() on the return value from strrev when you are
done with it.

> so you're returning a pointer to an array which is a pointer to a char
> (return value) -> array -> (char) array[1]
> if you want to access the value you're returning you'd have to access
> it as  &(return value);

That would definitely be a compiler error.  If you want to return a pointer
to the first element in the array, either of these will work:

   return array;


   return &array[0];


More information about the Courses mailing list