I'm attempting to swap chars in a string using xor bitwise operators instead of using a placeholder. However, it segfaults before doing the bitwise xor. Can anyone explain why is that the case? Is there something about chars that don't allow me to do bitwise operations?
void reverse(char *str) {
if (str == NULL || str == '\0') {
return;
}
//Obtain length of str
int length = 0;
for (char *ptr = str; *ptr != '\0'; ptr++) {
length++;
}
//Swap
for (int i = 0; i < (int)(length / 2); i++) {
str[i] ^= str[length - 1 - i];
str[length - 1 - i] ^= str[i];
str[i] ^= str[length - 1 - i];
}
}
int main() {
char *str = "bananas";
reverse(str);
printf("%s\n", str);
return 0;
}