Pointer to point to 3rd byte of an integer

go4expert's Avatar author of Pointer to point to 3rd byte of an integer
This is an article on Pointer to point to 3rd byte of an integer in C.
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: CPP
#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.
AhmedHan's Avatar, Join Date: Oct 2005
Go4Expert Member
union {
int i;
char c[4];
} vars;

vars.c[2] is the third byte of vars.i.

Last edited by AhmedHan; 18Oct2005 at 19:39.. Reason: forgot to write something
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by AhmedHan
union {
int i;
char c[4];
} vars;

vars.c[2] is the third byte of vars.i.
Yup thats also a nice way.
rahul.mca2001's Avatar, Join Date: Feb 2008
Ambitious contributor
good way