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"
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"
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:
#include <stdio.h>
class A {
public:
int i;
};
int main() {
A* a = new A();
int* i = &a->i;
printf("a: %p\na->i: %p\n", a, i);
return 0;
}
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 variable a
is 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:
$ ./a.out a: 40748 a->i: 40748
The addresses are the same because A
is 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.
In c++:
class A {
public: // note colon after public
int i;
}; // note semicolon after bracket
A *a = new A(); // note *a not a*
to print:
cout << ios::hex << &a->i << endl;
For me this seems to work ok.
&a->i should work. In your case since the class just has one public integer both the address of a and i will be the same.
You're on the right track, but from the compile error you mention, it sounds like you were typing "&a.i
"
class A
{
public:
int i;
};
...
A *a = new A();
int *i = &a->i;
This code appears to compile?
class A {
public:
int i;
};
int main() {
A *a = new A();
int *x = &a->i;
return 0;
}
The following works for me using g++
class A
{
public:
int m_i;
};
int
main()
{
A* a = new A();
int* i_ptr = &(a->m_i);
return 0;
}
I am guessing you mean A* a = ...
and not A a* = ...