Consider I have this piece of code:

#include <iostream>

using namespace std;

enum TEXTURE { SAND, GRASS, DIRT, ROCK, SNOW };

class grid
{
    public:
        TEXTURE type;
        string str;
};

grid layer[5];

int main()
{
    layer[0].str = "AAAAA";
    layer[1].str = "A A A";
    layer[2].str = " A A ";
    layer[3].str = "  A  ";
    layer[4].str = "AA AA";

    grid *ptr;
    ptr = &layer[0];

    if(*ptr.str.at(1) == 'A')
        cout << "TRUE!\n";
}

When I attempt to compile, it give me this error:
error: request for member str in ptr, which is of non-class type grid*
*I want to fix this so I can access the member variable str through ptr.
How do I fix it?

The dot operator and member function call have priority over the dereference operator. This means that the expression *ptr.str.at(1) is evaluated as *(ptr.str.at(1)), and that is why you get the error "str" is not a member of the pointer type grid*.

To fix it, you just need parentheses, like so: (*ptr).str.at(1). Or, C++ provides a shorter syntax for this very common operation, which is as follows: ptr->str.at(1), where the arrow p-> basically replaces the (*p)..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.