简体   繁体   中英

Using pointers to reverse a String

Trying to reverse a String in C using pointers and I can't seem to figure out what's wrong with my code. Does anyone know why this isn't working?

int main(void) 
{
    char sentence[100];
    printf("Enter any string: ");

    scanf("%[^\n]s", sentence);

    char *sPtr;
    sPtr = sentence;
    int length = 0;

    printf("Original string = %s\n", sentence);

    while (*sPtr != '\0') {
        ++length;
        ++sPtr;
    }

    printf("Reverse string = ");

    for (int i = length; i >= 0; --i) {
        printf("%c", *(sPtr + 1));
    }

    puts("");
    return 0;
}

The error is here:

while (*sPtr != '\0') {
    ++length;
    ++sPtr;
}

At this point the sPtr point at the end of the string so in the second loop it never decrement.

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+1));
}

A possible solution can be this:

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr));
    --sPtr;
}

You are always print a character past the end of the string.

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+1));
}

should be

for (int i = length-1; i >= 0; --i) {
    printf("%c", *(sPtr-(length-i));
}

or

   for (int i = length; i >= 0; --i) {
        sPtr--; //decrement first as sPtr will be pointing to \0 char
        printf("%c", *sPtr);
    }

This is the solution I came up with. Thanks for the help anyone provided!

while (*sPtr != '\0') {
    ++length;
    ++sPtr;
}

printf("Reverse string = ");

sPtr = sentence;

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+length));
    --sPtr;
}
  1. Write separate functions for such a tasks.
  2. When you test the function try to reduce number of unknown factors. In your case do not scanf just use known strings. scanf may fail and you will not know if it your function, or the user input.

Simple function, no library functions used.

char *reverse(char *str)
{
    char *head = str, *tail = str;

    if(str && *str)
    {
        while(*tail) tail++;
        tail--;
        while(tail > head)   
        {
            int ch = *tail;
            *tail-- = *head;
            *head++ = ch;
        }
    }
    return str;
}

https://godbolt.org/z/EgNLpF

After this loop

while (*sPtr != '\0') {
    ++length;
    ++sPtr;
}

the pointer sPtr points to the terminating zero. So in the next loop you are starting to output the string from the indeterminate character after the terminating zero.

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+1));
}

The expression *(sPtr+1) is not being changed in the loop.

Take into account that you are not reversing a string. You are trying to output a string in the reverse order. It is not the same. Also you are using an intermediate variable of the type int.

To reverse a string using only pointers the code can look the following way.

char *last = sentence;

while ( *last ) ++last;

if ( sentence != last )
{
    for ( char *first = sentence; first < --last; ++first )
    {
        char c = *first;
        *first = *last;
        *last = c;
    }
}

printf( "Reversed string = %s\n", sentence );

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    char *last = sentence;

    while ( *last ) ++ last;

    if ( sentence != last )
    {
        for ( char *first = sentence; first < --last; ++first )
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    printf( "Reversed string = %s\n", sentence );

    return 0;
}

Its output might look like

Enter any string: Hello Jordan
Reversed string = nadroJ olleH

You could write a separate function that reverse a string. Just move the code that reverses a string from main into a separate function like

#include <stdio.h>

char * reverse( char *s )
{
    char *last = s;

    while ( *last ) ++last;

    if ( s != last )
    {
        for ( char *first = s; first < --last; ++first )
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    return s;
}

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    printf( "Revresed string = %s\n", reverse( sentence ) );

    return 0;
}

If you want just to output a string in the reverse order using pointers then the program can be very simple.

Here you are.

#include <stdio.h>

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    const char *sPtr = sentence;

    while ( *sPtr ) ++ sPtr;

    printf( "Revresed string = ");

    while ( sPtr != sentence ) putchar( *--sPtr );
    putchar( '\n' );

    return 0;
}

Even more simply implementation you could make by means of a recursive function. For example

#include <stdio.h>

void reversed_output( const char *s )
{
    if ( *s )
    {
        reversed_output( s + 1 );
        putchar( *s );
    }
}

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    printf( "Revresed string = ");

    reversed_output( sentence );
    putchar( '\n' );

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM