Why doesn't this code work

class myclass {
public:
int *ptrarray;

myclass() {
ptrarray = new int[2];
*ptrarray[0] = 5; //here I want to set the value of  ptrarray[0] to 5, not its adress
*ptrarray[1] = 10;//here I want to set the value of  ptrarray[1] to 10, not its adress
}
};

int main() {
myclass a;
a->ptrarray[1] = 15; //now I want to change the value of ptrarray[1]
}

It seems this is supposed to be the way to reference a member pointer of a class, but I guess it is not? How would I fix this code so it will work?

Recommended Answers

All 2 Replies

Your object is not a pointer, so there's no need to use the arrow operator. Also, the [] operator is already dereferencing your pointer, so there's no need for an explicit dereference either:

class myclass {
public:
    int *ptrarray;
    myclass() {
        ptrarray = new int[2];
        ptrarray[0] = 5;
        ptrarray[1] = 10;
    }
};

int main()
{
    myclass a;
    a.ptrarray[1] = 15;
}
commented: yep +5

Thanks!

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.