I'm trying to reverse the string via void function, but segmentation fault occurs for "str" it's stored read-only memory (as I known from searching existing thread in the forum).
I tried to use strcpy(copy, str) in "reverse" function but it's just reversing the newly created char array "copy" which cannot be returned to main function. I don't want to use printf("%s", copy) in the reverse function to print the reversed string.
Is there anyway to reverse str
- Without changing it to
char str[] = "Hello"
- Without changing the code in
main()
function - Keep the function type of
reverse()
asvoid
?
void reverse(char* str)
{
int l = strlen(str);
char temp;
int j = length - 1;
for (int i = 0; i < j; ++i)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
--j;
}
}
int main(int argc, char* argv[])
{
char* str = "Hello";
reverse(str);
printf("%s\n", str);
return 0;
}