Search code examples
creversec-stringspointer-arithmeticfunction-definition

Why this C-program doesn't gives the reverse of given string?


Why this program doesnot gives reverse of the given string computer, though the length() function works fine(when I comment other codes and only run that part) and gives output correct but the second reverse() function is not giving any output.

#include <stdio.h>
#include <string.h>

 int length(char *);
 char *reverse(char *, int);

int main()
{
char word[] = "COMPUTER";
int count;

count = length("COMPUTER");

printf("%s", reverse(word, count));

}

int length(char *p)
{
int count;
for (count = 0; *(p + count) != '\0'; count++);
    
 return (count);
 }

 char *reverse(char *p, int count)
 {
char temp;
for (int i = 0; i < count / 2; i++)
{
    temp = *(p + i);
    *(p + i) = *(p - (count - 1) - i);
    *(p - (count - 1) - i) = temp;
}
return (p);
 }

Solution

  • These expression statements

    *(p + i) = *(p - (count - 1) - i);
    *(p - (count - 1) - i) = temp;
    

    are incorrect,

    It seems you mean

    *(p + i) = *(p + ( count - 1 ) - i);
    *(p + (count - 1) - i) = temp;
    

    Also instead of this statement

    count = length("COMPUTER");
    

    it will be more logically consistent to write

    count = length( word );
    

    Here is a demonstrative program.

    #include <stdio.h>
    
    size_t length( const char * );
    char * reverse( char *, size_t );
     
    int main(void) 
    {
        char word[] = "COMPUTER";
        size_t count = length( word );
    
        puts( reverse( word, count ) );
    
    }
    
    size_t length( const char *p )
    {
        size_t count = 0;
    
        while ( *( p + count ) != '\0' ) ++count;
        
        return count;
    }
    
    char * reverse( char *p, size_t count )
    {
        for ( size_t i = 0; i < count / 2; i++ )
        {
            char temp = *( p + i );
            *( p + i ) = *( p + count - 1 - i );
            *( p + count - 1 - i ) = temp;
        }
        
        return p;
    }
    

    The program output is

    RETUPMOC