次の単純な関数は、文字配列をその場で逆にする必要があります。
void reverse(char* str)
{
char* last = str;
// find end of the string
while(*last) {
++last;
}
// swap characters until the pointers meet in the middle
while(str < last)
{
--last;
char temp = *str;
*str = *last;
*last = temp;
++str;
}
}
int main()
{
char* a= "Hello";
reverse(a);
return 0;
}
コードがコンパイルされます。ただし、アクセス違反に関する実行時エラーがスローされます。デバッガーによると、犯人は次の行です。
char temp = *str;
なぜそれが起こるのですか?