543 views

1 Answer

1 votes
1 votes

Alignment is the issue for this program. If we want to convert int pointer to float pointer, that means u r casting integer pointer to float pointer and that is not same as conversion of int value to float value.

Here when p is pointing to i, that means p is pointing to the address of 10, which is an integer value. So, void pointer is converted to integer pointer. Now u want to value of integer pointer to a value of float pointer. There the problem comes. Though integer pointer is 4 Byte in 32 bit machine and float pointer is 64 Byte for same machine, but pointer conversion causes alignment issue. So, it will print 0.000000

chk code:

int a[8]={1,2,3,4,5,6,7,8};

printf("%f\n", *(float *)a);
printf("%f\n", *((float *)a+1));
printf("%f\n", *((float *)a+2));
printf("%f\n", *((float *)a+3));
printf("%f\n", *((float *)a+4));
printf("%f\n", *((float *)a+5));
printf("%f\n", *((float *)a+6));
printf("%f\n", *((float *)a+7));

Output will be

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000

The only pointer conversion can be done sometime  is

sizeof(unsigned char *) == sizeof(float)

The most common issue I read here called type punning

For more you can see

https://stackoverflow.com/questions/13881487/should-i-worry-about-the-alignment-during-pointer-casting

https://stackoverflow.com/questions/13633783/how-to-convert-a-float-pointer-to-an-int-pointer-in-c-c

https://stackoverflow.com/questions/30276645/typecasting-int-pointer-to-float-pointer

https://stackoverflow.com/questions/12397432/convert-pointer-to-float

edited by

Related questions

0 votes
0 votes
0 answers
1
garvit_vijai asked Sep 2, 2018
685 views
Please explain the output for the following program: #include<stdio.h>int main() { int i = 100; int *a = &i; float *f = (float *)a; (*f)++; pri...
2 votes
2 votes
2 answers
3
atulcse asked Jan 15, 2022
662 views
Consider the following programint find (int n) { int a = 1; for (i = 1; i < = n; i ++) for (j = 1; j < = i; j++) for (k = 1; k <= j, k++) a = a + 1; ...
1 votes
1 votes
1 answer
4
Na462 asked Jan 8, 2019
1,402 views
#include <stdio.h>main (){unsigned x = -10;int X = 20;if (X x) printf ("Hello");else{ printf ("%d",x); printf ("Jello"); }}