Cannot change char * - memory access violation

Why does he 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;
  }
+5
source share
3 answers

String literals are stored in a read-only memory section. Any attempt to modify the contents of a string literal causes an Undefined Behavior (segmentation error in most implementations).

Use an array of characters rather

char str[] = "HelloGuys";
+22
source

As Prasun already said, string literals do not change.

If you need a modifiable array of characters, it looks like this:

char str[] = "HelloGuys";
+1
source

, :

char str[] = "HelloGuys";   // change this line
int len = strlen(str);
for (int i=0; i<(len/2); ++i){
    char t = str[len-i-1];
    str[len-i-1] = str[i];
    str[i] = t;
}
0
source

All Articles