I am working on a project and I keep coming across this error that will not allow me to complete the project. When I initialize one of my pointers to point to an object that will be made during the execution of the program and I initialize it to NULL
. Then when I check to see what it is set to it returns a value of nil
. How is such a thing possible? I didn't believe that nil pointers existed in C. Is there any way around this?
struct order_line *front = NULL;
...
printf("Head: %p\n", front); // prints -> Head: (nil)
%p
in printf
formats a pointer type. This is going to distinguish a null-pointer and print (nil)
because it is a special value in the context of a pointer. If you want to output 0 for a null pointer, cast the pointer to an integer and use %d
instead:
printf("Head: %d\n", (int) front);
Original answer as it may still be useful:
NULL
is a macro defined as 0
or ((void *) 0)
, so if you set a pointer to NULL
it's exactly the same as setting it to 0
. This works for the purposed of declaring null pointers because the memory at address 0 will never be allocated to your program.
When you print a pointer using printf("%p", somePtr)
, it is printed in an implementation-defined manner, as per this quote from the POSIX printf specification (similar wording exists in the C99 specification also).
The argument must be a pointer to void. The value of the pointer is converted to a sequence of printable characters, in an implementation-dependent manner.
I guess, that this means if the pointer is NULL
, it may print it however it wants, including printing it as nil
or 0x00000000
or 0
.
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