I have the following code which its main purpose is reverse the characters of a string. So, for example, the string I love cats
would be converted to stac evol I
.
#include <string.h>
#include <stddef.h>
#include <stdio.h>
void reverseString(char *str)
{
int size = strlen(str);
char *end = str + size - 1;
char tmp;
while (end > str) {
tmp = *str;
*str = *end;
*end = tmp;
end--;
str++;
}
}
int main()
{
char *str = "Y U SEGMENTATION FAULT?";
reverseString(str);
}
When I run this, I get a segmentation fault, and I fail to see why. Also, another question I have is the time complexity (Big O) of this function. I believe it should be O(n/2), since I am not going through all the array but just the half of it. Am I right?