私はC++を初めて使用しており、ダブルポインタを使用して多次元配列のコードを記述しようとしています。これは私のコードです:値を代入しようとするとC++コードが壊れます
クラス宣言:
class magicMat{
private:
int** ptrnum;
public:
void init(int);
void Display(int);
void set(int);
void message();
void errorhandling(int);
};
関数定義:
void magicMat::init(int input)
{
ptrnum=new int*[input];
for (int row=0;row<input;row++)
ptrnum[row]=new int[input];
for(int x=0;x<input;x++)
{
for (int y=0;y<input;y++)
{
*(ptrnum[x]+y)=0;
}
}
}
void magicMat::set(int input)
{
int row=1,col=input/2,otherdiag=0;
for(int value=1;value<=input*input;value++)
{
if (*(ptrnum[row]+col)>0)
{
row=row+2;
if(row>input)
row=row-input;
col--;
if(col<1)
col=input;
}
*(ptrnum[row]+col)+=value;
*(ptrnum[0]+col)+=value;
*(ptrnum[row]+0)+=value;
if (row==col)
*(ptrnum[0]+0)+=value;
if (row+col==input+1)
otherdiag+=value;
/* */
/* Determine where new row and col are */
/* */
row--;
if (row < 1) /* If row exceeds side then */
row = input; /* goto other side. */
col++;
if (col > input) /* If col exceeds side then */
col = 1;
}
}
主な機能:
int main()
{
int num;
magicMat newMat;
newMat.message();
while(1)
{
cin>>num;
if (cin.good())
{
newMat.errorhandling(num);
}
else if (!isdigit(num))
{
cout<<"Please enter only digits"<<endl;
}
newMat.init(num);
newMat.set(num);
newMat.Display(num);
}
cout<<"\nBye bye!\n"<<endl;
return 0;
}
それはinit
機能で動作しますが、set
で関数私はそれが最初に破る値をチェックしようとするset
データ関数内のif
ステートメント。
'ptrnum [x] [y]'だけを試してください。本当の理由がない場合は、代わりにベクトルのベクトルを使用してください。それはずっと安全です。 'ベクトル>行列; –
chris
よく私はダブルポインタを使用するように求められています。これは宿題です。申し訳ありませんHW.Doneと今すぐそれをタグしませんでした – SB26
ちなみに、" init "関数を使用すると、 C++。オブジェクトはコンストラクタを使用して初期化する必要があります。つまり、初期化することを忘れて*忘れることはありません。コメントを投稿するには、http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming) – HostileFork