class A {
public: int i;
};
A *a = new A();
How to get the address of a->i? I tried &a->i and also &(a->i) but those generate compile time errors:
“left of ‘.i’ must have class/struct/union type”
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You have not provided the same code you tried to compile. Always copy and paste. The tells in your code are that you don’t have a syntactically correct class declaration or variable declaration, and that your error message talks about “.i” when you’ve claimed you’ve only used
a->i. Here’s working code:Ultimately, the syntax you say you tried for getting the address of the member was correct. The syntax the error message says you tried was
a.i. That doesn’t work, and for the reason the error message gave. The variableais not a class, struct, or union type. Rather, it’s a pointer to one of those types. You need to dereference the pointer to get at the member.When I run it, I get this:
The addresses are the same because
Ais a simple class, so this output is to be expected. The first member is frequently placed at the very start of a class’s memory. Add a second member variable to the class and get its address; you should see different values then.