I am new to C++ and am trying to write code for a multi-dimensional array using double pointers. This is my code:
Class Declaration:
class magicMat{
private:
int** ptrnum;
public:
void init(int);
void Display(int);
void set(int);
void message();
void errorhandling(int);
};
Function definitions:
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;
}
}
Main function:
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;
}
It works in the init function but when in the set function I try to check the value it breaks at the first if statement in the set data function.
You are stepping outside the bounds of your array. Just as an example, if I run your code and enter
5as my first digit which sets the value ofinputto5, look at these lines at the end of yoursetfunction:At the end of the first time through the loop in your
setfunction, right before these lines,rowis equal to1. These three lines execute and as a result,rowis set equal to5.At the beginning of your next loop in
set, you do this:The problem is that
ptrnumis a 5×5 array, which means valid indexes are from 0-4. At the end of the previous loop, however, you setrowequal to5and as a result, you’re indexing outside the bounds ofptrnumand thus crashing your program.I highly recommend either stepping through your code in a debugger or if you’re not sure how to do that, at least put in a bunch of
coutstatements in yoursetfunction so you can check that the variables are getting set to what you think they should get set to.Good luck!