Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Error: expression must have a pointer type" when using the "this" keyword

Tags:

c++

this

So I made a parent class, which i will call Parent that has a Square* grid member variable. The grid variable is a pointer to a large array of Squares, which contain key member variables. (Think of this project as a hashtable) The problem is I am making a function in the Parent class that edits the key variables in the Square array, and getting an error. This line of code compiles:

this->grid = new Square[row*col];

but this line does not compile:

this->grid[i*col + j]->key1 = j;

it underlines this and says expression must have a pointer type. I was wondering if anyone had ideas to what i may be doing wrong?

void Parent::initialize(int row,int col) {
    this->grid = new Square[row*col];
    for(int i = 0; i < row; i++) {
        for(int j = 0;j < col; j++) {
            this->grid[i*col + j]->key1 = j;
            this->grid[i*col + j]->key2 = i;
        }
    }
like image 913
necroncryptek Avatar asked Oct 27 '12 20:10

necroncryptek


2 Answers

You have to use

this->grid[i*col + j].key1
this->grid[i*col + j].key2

That is because even if it is true that your grid is a pointer, you have allocated in the are pointed by its memory an array of Square object. So when you use the [] operator you are obtaining an object of type Square and not a Square* and for a Square object you hve to use the . operator and not the -> operator.

like image 186
il_guru Avatar answered Nov 15 '22 13:11

il_guru


I guess this->grid is of type Square*, so this->grid[0] is of type Square& and you must use . (dot) not -> (arrow) to access members from Square&. To use arrow for expression expression must have a pointer type...

this->grid[i*col + j]->key2
//                   ^^: this->grid[i*col + j] is not a pointer 
this->grid[i*col + j].key2
//                   ^ use dot to access key2 and key1 too
like image 41
PiotrNycz Avatar answered Nov 15 '22 13:11

PiotrNycz