Can we save memory address in int variable?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Aesha
    New Member
    • Nov 2010
    • 1

    #1

    Can we save memory address in int variable?

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

    for eg.

    Code:
    class node
    {
    char a;
    node *link;
    }
    
    int main()
    {
    int i=10;
    node *ptr=NULL;
    ptr=new node;
    //i want to store value of ptr in i or character array of 4
    
    return 0; 
    }

    please help me as i m stuck in my project
    Last edited by NeoPa; Nov 3 '10, 01:56 AM. Reason: Please use the [code] tags provided.
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    Aesha,

    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.

    union:
    Code:
    node *p = new node();
    int i;
    union {
      node *p;
      int i;
    } u;
    u.p = p;
    i = u.i;
    clean typecast:
    Code:
    int i = (int)(void*)(new node());
    address games:
    Code:
    node *p = new node();
    int i = *(int*)(void*)&p;

    Comment

    Working...