Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Pointer to point to 3rd byte of an integer (http://www.go4expert.com/articles/pointer-3rd-byte-integer-t364/)

 go4expert 18Jun2005 12:01

Pointer to point to 3rd byte of an integer

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 18Oct2005 19:38

Re: Pointer to point to 3rd byte of an integer

union {
int i;
char c[4];
} vars;

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

 shabbir 18Oct2005 19:59

Re: Pointer to point to 3rd byte of an integer

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 6Mar2008 13:37

Re: Pointer to point to 3rd byte of an integer

good way

 All times are GMT +5.5. The time now is 15:50.