Modify the content of char* str
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
char str[] = "Hello"
main()
function reverse()
as void
? 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("%sn", str);
return 0;
}
The problem is you cannot modify string literals.
Try like this:
char str[] = "Hello";
reverse(str);
above, str
is no longer a string literal, it's an array initialized to {'H', 'e', 'l', 'l', 'o', '