I was playing around with pointers, and I tried to initialize a pointer variable with a value and not a memory location.
If I am initializing a pointer with a non-zero value, and it is clearly giving me a compile time error.
int *p = 1;
main.c:14:14: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
int *p = 1;
^
However, if I initialize it as value 0, it doesn't give me a compile time error.
int *p = 0; //no compile time error but segmentation fault
Why is this so? Is there a valid memory address like 0? Normally, an address location is shown as 0xffffff
or similar way. How is 0 interpreted into a memory location?
Thanks
From the C11 Standard (draft):
6.3.2.3 Pointers
[...]
3 An integer constant expression with the value 0, or such an expression cast to type
void *
, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
Usualy 0
represent a "no address" asNULL
. When you use it that way you can check:
if (p) {
doSomthingWith(*p)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With