can't modify char* - Memory access violation
Why does it say "Memory access violation"?
char* str = "HelloGuys";
int len = strlen(str);
for (int i=0; i<(len/2); ++i){
char t = str[len-i-1];
str[len-i-1] = str[i]; //error
str[i] = t;
}
Solution 1:
String literals are stored in read only section of memory. Any attempt to modify the contents of a string literal invokes Undefined Behaviour (segmentation fault on most implementations).
Use an array of characters rather
char str[] = "HelloGuys";
Solution 2:
As Prasoon already said, string literals are not modifiable.
If you need a modifiable array of chars have it like this:
char str[] = "HelloGuys";
Solution 3:
The behaviour is undefined if a program attempts to modify any portion of a string literal (most compiler chose to raise a "Memory access violation" error). The most important thing is to identify when you are trying to modify string literals and when you are not.
This is ok:
char str[] = "string literal";
str[0] = 'S';
You have made a copy of the string literal. You are not modifying the string literal, but the array str.
This is not ok:
char *str = "string literal";
str[0] = 'S';
You never made a copy of the string; the pointer is pointing to the string literal itself. You are attempting to modify the string literal.