I have Wrote the Following Code Snippet but it is not working. Can anyone help me? Where i am Wrong ??
char *xstrrev(char *string)
{
int len=0,i=0;
char *reverse;
while(*string!='\0')
{
len++;
string++;
}
len=len-1;
while(len>=0)
{
*reverse=string[len];
reverse++;
len--;
}
*reverse='\0';
return reverse;
}
int main()
{
char name[10];
scanf("%s",name);
printf("%s",xstrrev(name));
return 0;
}
I am unable to return whole string in the main function
Three problems:
[1] reverse
not pointing to valid memory area.
[2] returning reverse
will return the last byte address of string reverse
. so need to store the start of reverse
and return the start of reverse
.
[3] string
is completely parsed while calculating the length, so again, start of original string needs to be saved and used subsequently
char *xstrrev(char *string)
{
char *original_string = string;
int len=0,i=0;
//[1] char *reverse;
while(*string!='\0')
{
len++;
string++;
}
//[3] till here "string" is completely parsed, so it points to past the end.
char *reverse = (char*)malloc(len + 1);
char *reverse_to_be_returned = reverse;
len=len-1;
while(len>=0)
{
//[3] *reverse=string[len];
*reverse = original_string[len];
reverse++;
len--;
}
*reverse='\0';
//[2] return reverse;
return reverse_to_be_returned;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments