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;
}
Answer
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', '\0'}
, so you can modify it's contents if you want.
Or you can use malloc()
char *str = malloc(6);
if (str != NULL)
{
strcpy(str, "Hello");
reverse(str);
fprintf(stdout, "%s\n", str);
/* And never forget to `free' */
free(str);
}
When defining string literals use const
to protect it from being modified, at least from accidentally doing so.
There is no way to satisfy these requirements
Without changing it to
char str[] = "Hello"
Because you cannot modify string literals
Without changing the code in
main()
function
Because that would require the program to modify a string literal and YOU CAN'T
The third requirement, does not impose any problem at all.
No comments:
Post a Comment