Pointer to point to 3rd byte of an integer

Discussion in 'C' started by go4expert, Jun 18, 2005.

  1. go4expert

    go4expert Moderator

    Joined:
    Aug 3, 2004
    Messages:
    306
    Likes Received:
    9
    Trophy Points:
    0
    One of the tricky question in interview comes out is

    How do you point to the third byte of an integer. Assumption that integer is 4 byte. Here is the code to do the same

    Code:
    #include <iostream>
    using namespace std;
    
    int main(int argc, char *argv[])
    {
    	int i = 35;              //integer variable
    	int *ip = &i;            //Integer pointer
    	void *vp = (int*)ip;     //Void pointer for type casting
    	char *cp = (char*)vp;    //Char pointer
    	cp++;                    //Point to second byte
    	cp++;                    //Point to third byte
    	return 0;
    }
    
    The concept is to have a void pointer to cast the integer pointer to the character pointer and increment that to point to the any byte location you wish to by simply incrementing it. Assumption char pointer is 1 byte.
     
  2. AhmedHan

    AhmedHan New Member

    Joined:
    Oct 11, 2005
    Messages:
    30
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.stirve.com
    union {
    int i;
    char c[4];
    } vars;

    vars.c[2] is the third byte of vars.i.
     
    Last edited: Oct 18, 2005
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,376
    Likes Received:
    388
    Trophy Points:
    83
    Yup thats also a nice way.
     
  4. rahul.mca2001

    rahul.mca2001 New Member

    Joined:
    Feb 13, 2008
    Messages:
    103
    Likes Received:
    0
    Trophy Points:
    0

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice