c - char to integer pointer conversion -


void main() {  char *s="abcdefg";  clrscr();   int *ptr=(int *)s;  printf("%c %d\n",*(ptr+1),*(ptr+1));          //op :- c 17475  printf("%c %d\n",*(s+1),*(s+1));              //op :- b 66   getch(); } 

i know integer pointer increments 2 bytes whereas char pointer increments 1 byte. here when int pointer increments 1, c printed (only first byte considered). because have %c specifier ?

also, not able understand how 17475 printed output. in second case 66 ascii value of b.

can me?

to start important notice code has undefined behavior. means can not generated output solely referring c standard. output may/will differ system system , systems may not able execute code.

the problem have number of char (a char array) access using int pointer. not allowed.

however, on specific system (your system) possible consideration why output looks does. but remember not valid c code. note: pointed out antti haapala code syntax valid - it's behavior of program undefined

the string (aka char array) placed somewhere in memory like:

address |    bin    | hex | dec | ascii char --------------------------------------------  base   | 0100 0001 |  41 | 65  |  base+1 | 0100 0010 |  42 | 66  | b  base+2 | 0100 0011 |  43 | 67  | c  base+3 | 0100 0100 |  44 | 68  | d  base+4 | 0100 0101 |  45 | 69  | e  , on 

notice memory holds binary values. hex, dec, ascii columns "human" view of same binary value.

your pointer s has value base, i.e. points memory location holds value 0100 0001 (aka a).

then make ptr point base well.

when printing (i.e. printf("%c %d\n",*(ptr+1),*(ptr+1));), ptr+1 point location depends on size of integers (which differs system system). since have size of int being 2, ptr+1 location base + 2, i.e. 0100 0011 (aka c).

so first part of statement:

printf("%c %d\n",*(ptr+1),*(ptr+1));         ^^       ^^^^^^^^ 

prints c, i.e. char @ location base+2.

the second part

printf("%c %d\n",*(ptr+1),*(ptr+1));            ^^             ^^^^^^^^ 

prints integer value located @ base+2. (note - illegal there no integer there let's forget moment).

in case int 2 bytes. used bytes c (hex: 0x43) , d (hex: 0x44). value printed depend on endianness of system.

big endian (msb first) give:

0x4344 17220 in decimal 

little endian (lsb first) give:

0x4443 17475 in decimal 

so seems system little endian.

as can see lot of stuff system dependant , c standard point of view impossible tell out be.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -