Christopher Benson-Manica said:
Broken. What makes you suspect that 20 is an appropriate value for a
pointer to an integer?
What's surprising is that his compiler thought it was appropriate.
A compiler might allow assigning an integer value to a pointer as an
extension, but if the code is compiled in strict mode (might be called
"ansi" or "iso", depending on the compiler), the compiler is required
to issue a diagnostic.
[...]
Broken. The size of a pointer to an integer need not be equal to
sizeof(int).
Size matters not. Using "%d" to print a pointer value invokes
undefined behavior (though it will often do what you expect anyway).
It can fail even if int and int* happen to have the same size.
The correct way to print an int* value is:
printf("%p", (void*)p);
Also, the original code, if it doesn't blow up, will probably print
the values adjacent to each other; you won't be able to tell where one
ends and the other begins. Rather than
int *p=20;
printf("%d",*p);
printf("%d",p);
you might try this:
int *p = (int*)20;
printf("*p = %d\n", *p);
printf("p = %p\n", (int*)p);
Of course this could still invoke undefined behavior, since (int*)20
is unlikely to be a valid address.
Here's a program that actually works:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int *p = malloc(sizeof *p);
if (p == NULL) {
printf("malloc failed\n");
}
else {
*p = 20;
printf("*p = %d\n", *p);
printf("p = %p\n", (void*)p);
}
return 0;
}