1

I'm trying to reverse a c string. I know of easier ways to do this but I was trying to practice some pointers. This compiles but returns a null string and I do not understand why. What am I missing here?

#include <stdio.h>
#include <stdlib.h>
int main(){
    char *forwards, *backwards;
    forwards = "hello";
    backwards = (char*) malloc( strlen(forwards) );
    int i;
    for( i = strlen(forwards) - 1; i >=0; --i )
            backwards[ strlen(forwards) - i ] = forwards[i];
    printf("%s", *backwards );
    return 0;
    }

2 Answers 2

2

You have multiple errors.

First of all the indices calculated are wrong, you should subtract 1 from the backwards index, eg:

for (i = strlen(forwards) - 1; i >= 0; --i )
{
  printf("%d -> %lu\n", i, strlen(forwards) - i - 1);
  backwards[ strlen(forwards) - i - 1] = forwards[i];
}

/* prints
4 -> 0
3 -> 1
2 -> 2
1 -> 3
0 -> 4

Mind that there is no reason to have the loop counting down, for (i = 0; i < length; ++i) would have worked exactly in the same way

The second error is that strlen doesn't include the NUL terminator so your backwards should be allocated as malloc(strlen(forwards)+1).

The third error is the fact that you are not setting the terminator on the reverse string, you must place it by hand, with something like:

backwards[strlen(forwards)] = '\0';

The last error is the fact that you are dereferencing the pointer in the printf, which you shouldn't do, so it should be

printf("%s\n", backwards);
               ^
               no * here
Sign up to request clarification or add additional context in comments.

1 Comment

And another problem is repeatedly calling strlen(forwards) in the loop when the value doesn't change.
1

Your loop will result in:

backwards[1] = forwards[4];
backwards[2] = forwards[3];
backwards[3] = forwards[2];
backwards[4] = forwards[1];
backwards[5] = forwards[0];

You'll want to change your code to:

backwards[strlen(forwards) - i - 1] = forwards[i];

In C, strings must end with '\0', so make sure you do:

backwards = malloc(strlen(forwards) + 1);
// ...
backwards[strlen(forwards)] = '\0';

Also, to print the string:

printf("%s", backwards); // no dereferencing the pointer

4 Comments

And a suggestion, instead of calling strlen(forwards) multiple times, assign it to a int len = strlen(forwards) and use the variable when needed.
Hey ericbn That worked, thanks. Why do I not need to dereference the pointer?
And C-String is necessary to end with a null character.
@mreff555: dereferencing a char* yields a char which is a single character, not a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.