简体   繁体   中英

What happens if I assign to an int pointer a float variable address and vice-versa?

I was wondering what would happen if I gave an int pointer a float variable address and vice-versa, so I tried it but couldn't exactly understand what's happening so if anyone can explain I would be grateful.

int n = 5;
float f = 1.21;
float *pf = &n;
int *pn = &f;

printf("%p  %p\n", pn, pf);
printf("%p  %p\n", &f, &n);
printf("%d   %f \n", *pn, *pf);
printf("%f   %d \n", n, f);
printf("%d  %f \n", n, f);

Output:

0xffffcba8  0xffffcbac
0xffffcba8  0xffffcbac
1067114824   0.000000
0.000000   0
5  1.210000

There is a number of instances of undefined behavior in your code:

  • int n = 5; : OK
  • float f = 1.21; : OK
  • float *pf = &n; initializes a pointer with the value of a pointer to a different type. The C Standard makes no guarantees as to what this does nor as to what happens when you dereference this pointer. With -Wall -W , you would definitely get a warning for this, which you could silence with a cast: float *pf = (float *)&n; , yet the result is the same, dereferencing the pointer has undefined behavior.
  • int *pn = &f; same as above.
  • printf("%p %p\\n", pn, pf); -> you should cast the pointers as (void *) because %p expects a void * as an argument. On some rare systems (old Cray systems IIRC), pointers to int , float and void may have different representations, causing this call to printf to behave in unexpected ways. Use this instead:

     printf("%p %p\\n", (void *)pn, (void *)pf);
  • printf("%p %p\\n", &f, &n); -> same problem. Use this instead:

     printf("%p %p\\n", (void *)&f, (void *)&n);

    The output is correct and the same for both expressions because your system is regular, but the C Standard does not guarantee it.

  • printf("%d %f \\n", *pn, *pf); this one is correct but dereferencing the pointer has undefined behavior.
  • printf("%f %d \\n", n, f); passing value of types different from the expected types has undefined behavior. The output you get is incorrect.
  • printf("%d %f \\n", n, f); this one is correct and the output is 5 1.210000 as expected.

Chqrlie´s answer is way better than mine. Please re-accept his answer.


You should not abuse pointers and objects - Even not for curiosity reasons. The results of the 1., 2. and the 5. printf command are correct, but the results of the 3. and 4. printf command are products of Undefined Behavior, thus noone can explain them.

For more information about Undefined Behavior: Undefined, unspecified and implementation-defined behavior

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM