Thread: Pointer in c

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    8
    Rep Power
    0

    Pointer in c


    Hello,
    OS:-windows 7(64bit)

    char *p;
    which is pointing int data,
    (for example,p is pointing at 3456 location on memory
    memory:::>.....|....|(2 3 4 5)|....|
    ............................^
    ............................p(address:-3456)
    now how to get that int data in char *p
    and copy the data from that pointer to int variable?
    how to do this?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    Something like
    int var;
    memcpy(&var,p,sizeof(var));


    Some misguided souls would suggest something like this
    int var = *(int*)p;
    but they should really read up on alignment exceptions before trying to type any more code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    8
    Rep Power
    0
    Originally Posted by salem
    Something like
    int var;
    memcpy(&var,p,sizeof(var));


    Some misguided souls would suggest something like this
    int var = *(int*)p;
    but they should really read up on alignment exceptions before trying to type any more code.
    Thank you salem,

    will it copy whole 2345 or first byte'2' only?
    and another thing suppose that 2345 is address and from that location if I want to get data in to char pointer, how to do this?

IMN logo majestic logo threadwatch logo seochat tools logo