0

重複の可能性:
この C コードがセグメンテーション違反を引き起こしているのはなぜですか?

私のコード:

    void strrev(char *str) {
  char temp, *end_ptr;

  /* If str is NULL or empty, do nothing */
  if( str == NULL || !(*str) )
    return;

  end_ptr = str + strlen(str) - 1;

  /* Swap the chars */
  while( end_ptr > str ) {
    temp = *str;
    *str = *end_ptr;
    *end_ptr = temp;
    str++;
    end_ptr--;
  }
}
void main() {
    char temp;
    char* x = "Hel2313lo123";
    //temp = *x;
//  strReverse(x);
    strrev(x);
    printf("\n%s", x);
}

実際、関数 strrev() は次のコードから直接コピーされています: How do you reverse a string in place in C or C++?

これを実行しようとするたびに、セグメンテーション違反が発生します。なぜそれが起こっているのでしょうか?

ありがとう!

4

1 に答える 1

2

char* x = "Hel2313lo123";読み取り専用の C 文字列を意味します。配列が必要ですchar x[] = "Hel2313lo123";

于 2013-01-06T18:28:17.690 に答える