user1762250
user1762250

Reputation: 125

Getting memory address of class member variable (non-dynamic)

I want to print the memory address (i.e. 0x7ffff0...) of a variable in my class, but it only gives me the value of the object.

I'm just doing this to learn. I don't think my syntax is incorrect. I try two ways and neither works. I would appreciate help on why this doesn't work.

#include <iostream>
using namespace std;
class test{
public:
char i;
};

int main(){
test x;
x.i='w';
char * y = &(x.i);
cout<<"address : " <<&x.i<<endl;
cout<<"address : " <<y<<endl;
}

Output:

address : w
address : w

Upvotes: 0

Views: 1699

Answers (2)

Beed
Beed

Reputation: 460

Try casting the pointer to an integer type. Then print the integer. Try intptr_t.

Upvotes: 0

Krum
Krum

Reputation: 498

You should cast the pointer to a void* before passing it to the stream. You're passing a char* which is interpreted as a null-terminated string.

Upvotes: 1

Related Questions