can't modify char* - Memory access violation

前端 未结 4 1902
梦如初夏
梦如初夏 2020-11-30 10:26

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[l         


        
相关标签:
4条回答
  • 2020-11-30 11:06

    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.

    0 讨论(0)
  • 2020-11-30 11:11

    To fix this, use an array instead of a pointer to read-only memory:

    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 讨论(0)
  • 2020-11-30 11:18

    As Prasoon already said, string literals are not modifiable.

    If you need a modifiable array of chars have it like this:

    char str[] = "HelloGuys";
    
    0 讨论(0)
  • 2020-11-30 11:22

    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";
    
    0 讨论(0)
提交回复
热议问题