Reputation: 1111
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;
}
Upvotes: 1
Views: 52
Reputation: 10958
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
Upvotes: 1
Reputation: 133587
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
Upvotes: 2