When you declare int *ptr
, you're creating a variable called ptr
which can hold the address of an int
. When you dereference it in *ptr = 5
, you're saying "store 5 in the address that ptr
points to" - but as ptr
is uninitialised, where it points to is undefined. So you're invoking undefined behaviour.
An int *
does not store an int
, but just an address that points to one. There still has to be a real int
at that address.
If you want to allocate an int
that exists outside of the local scope, you can use malloc
. A simple conversion of your example without error checking:
int *ptr = malloc(sizeof(int));
*ptr = 5;
printf(" %d\n",*ptr);
If you do use malloc
, just remember to free
the allocated memory when you're finished:
free(ptr);