By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,972 Members | 883 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,972 IT Pros & Developers. It's quick & easy.

Can we save memory address in int variable?

P: 1
If we know that sizeof(int) and sizeof(pointer) is same .How to save that pointer value in int?

for eg.

Expand|Select|Wrap|Line Numbers
  1. class node
  2. {
  3. char a;
  4. node *link;
  5. }
  7. int main()
  8. {
  9. int i=10;
  10. node *ptr=NULL;
  11. ptr=new node;
  12. //i want to store value of ptr in i or character array of 4
  14. return 0; 
  15. }

please help me as i m stuck in my project
Nov 3 '10 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 983

Please tell me this isn't a homework problem. We see variations of this question crop up on Bytes quite freequently.

That said, you can transform the value, but why do you need to violate the abstraction of a pointer? I really am curious, so please do tell me what you want to accomplish by doing this.

There are a host of ways of accomplishing what you want.

Expand|Select|Wrap|Line Numbers
  1. node *p = new node();
  2. int i;
  3. union {
  4.   node *p;
  5.   int i;
  6. } u;
  7. u.p = p;
  8. i = u.i;
clean typecast:
Expand|Select|Wrap|Line Numbers
  1. int i = (int)(void*)(new node());
address games:
Expand|Select|Wrap|Line Numbers
  1. node *p = new node();
  2. int i = *(int*)(void*)&p;
Nov 3 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.