Reputation: 75
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
Upvotes: 2
Views: 364
Reputation: 15062
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
Upvotes: 1
Reputation: 144951
There is a number of instances of undefined behavior in your code:
int n = 5;
: OKfloat f = 1.21;
: OKfloat *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.Upvotes: 3