저는 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;
}
}
주요 기능 : set
에
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
문
'ptrnum [x] [y]'만 시도해보십시오. 하지 않을 진짜 이유가 없다면 대신 벡터 벡터를 사용하십시오. 훨씬 더 안전합니다. '> 행렬; –
chris
글쎄 이중 포인터를 사용하라는 요청을 받았습니다. 숙제입니다. 죄송합니다. HW로 태그를 지정하지 않았습니다. 지금 작성하십시오. – SB26
덧붙여 말하자면 "init"함수를 사용하는 것은 일반적으로 C++. 객체는 생성자를 통해 초기화되어야합니다. 이렇게하면 실수로 초기화하는 것을 잊을 수 없습니다. http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming) – HostileFork