2012-04-06 21 views
0

エラーが発生したときにこのコードを実行していました。 デバッガを実行すると、「プログラムでアクセス違反(セグメンテーションフォルト)エラーが発生しました」というエラーが発生しました。Dev C++アクセス違反(セグメンテーションフォルト)エラー

/* Statcstr.cpp 
* Le stringhe sono in realta' array static 
*/ 
#pragma hdrstop 
#include <condefs.h> 
#include <string.h> 
#include <iostream.h> 
//--------------------------------------------------------------------------- 
#pragma argsused 
int Modifica(); 
void Attesa(char *); 
int main(int argc, char* argv[]) { 
while(Modifica()); 
Attesa("terminare"); 
return 0; 
} 
int Modifica() { 
static unsigned int i = 0; // Per contare all'interno della stringa 
char *st = "Stringa di tipo static\n"; 
if(i < strlen(st)) { // Conta i caratteri nella stringa 
cout << st; // Stampa la stringa 
st[i] = 'X'; //<--- THIS IS THE FAILING INSTRUCTION 
i++; // Punta al prossimo carattere 
return 1; 
} else 
return 0; // Indica che la stringa e' finita 
} 
void Attesa(char * str) { 
cout << "\n\n\tPremere return per " << str; 
cin.get(); 
} 

どうすれば解決できますか教えてください。 ありがとうございました

答えて

2

文字列リテラルの変更は未定義の動作です。

char *st = "Stringa di tipo static\n"; 
      //this resides in read-only memory 

これはC++であることから、あなたはstd::stringを使用する必要があり、

char st[] = "Stringa di tipo static\n"; 
      //this is a string you own 

として宣言してくださいか。

+0

このように、文字列は文字配列として扱われますか?文字列に関する情報をありがとう、私は知らなかった(私はプログラミングでは新しい)...理由はあるのだろうか?とにかく、この方法でうまく動作します! – user1318308

+0

@ user1318308yes。 –

関連する問題