Problem with my string reverse code
Hi all, I was just playing around with strings, and I tried doing a string reverse using pointers, however, it did not turn out as I wanted. I tried using arrays and it works, but I cant do the same for pointers. As I'm still quite new to pointers, please guide me. Thank you. The code is as below:
Code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char * reverseString(char *);
int main()
{
char *input, *p;
input = malloc(100);
fgets(input, 100, stdin);
if((p=strchr(input, '\n'))!=NULL)
*p = '\0';
printf("%s\n", reverseString(input));
return 0;
}
char * reverseString(char *originalString)
{
char *temp;
int length = 0;
length = strlen(originalString);
temp = malloc(length);
temp = ???; /* I should assign temp to point somewhere? */
/* assign pointer to point at end of string */
originalString = &(originalString[length-1]);
while(length)
{
*temp++ = *originalString--;
length--;
}
return temp;
}