Here I am trying to swap two characters in a string using XOR operation. But GCC compiler throws me a segmentation fault.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str = "welcome";
str[0] = str[0] ^ str[1]; // Segmenation fault here
str[1] = str[0] ^ str[1];
str[0] = str[1] ^ str[0];
printf("%s", str);
return 0;
}
You can’t change literals in C.
strpoints to read-only memory.Try instead:
There is a C FAQ on the subject.