There are lots of problems in your code:
- If you create something with new, you have to call also delete on that object
- the_field should be private
- you don’t need to define i and j in the class, because they are defined in the for loop already
- you are ignoring what does the create_field() method returns
- the size of the grid is not dynamic (use width and height in simialr situations)
- the_field is pointer to a pointer (2D array in your case), but you are creating just the columns (the rows have to be created also)
- …
I have fixed it for you, please try it.
#include <iostream>
using namespace std;
class field
{
private:
char** the_field;
int width;
int height;
public:
// constructor
field(int w, int h);
// destructor
~field();
// method
void print();
};
field::field(int w, int h)
{
width = w;
height = h;
the_field = new char*[width];
for (int i=0; i<width; i++)
{
the_field[i] = new char[height];
for (int j=0; j<height; j++)
{
the_field[i][j] = 'O';
}
}
}
field::~field()
{
for (int i=0; i<width; i++)
delete[] the_field[i];
delete[] the_field;
}
void field::print()
{
for(int i=0; i < width; i++)
{
for(int j=0; j < height; j++)
{
cout << " " << the_field[i][j] << " ";
}
cout << "\n";
}
}
int main()
{
field* myfield = new field(14, 14);
myfield->print();
delete myfield;
return 0;
}
3
solved error: unexpected unqualified-id before ‘.’ token.