I am experimenting with pointers in C. I wrote this code.
int i1;
int i2 = 50;
int *intptr1;
int *intptr2;
intptr1 = &i1;
intptr2 = &i2;
intptr1 = intptr2;
printf("\nvalue of intptr1: %d\n", *intptr1); /*prints 50*/
dubptr1 = (double *)intptr1;
printf("\nvalue of dubptr1: %f\n", *dubptr1); /*prints 0.0000*/
I would have expected the last statement to print 50.0000. Is it actually supposed to print 0.0000 or did I make a mistake somewhere and if I did please help me understand where?
No, it won't necessarily print 0.000 it can even print some garbage values also in different compilers. Here, the mistake is the value is in int data type which is of 4 bytes whereas you are converting that address into double which is 8 bytes. So, double pointer is now pointing to 8 bytes so extra 4 bytes of memory can be anything due to which it is reading 8 bytes of memory in double precision floating point representation and providing different answer. Instead you can convert the value rather than converting the address data types
Get Answers For Free
Most questions answered within 1 hours.