Reputation: 135
#include <stdio.h>
int main(void)
{
struct findEntry
{
int value;
struct entry *next;
};
struct entry n1, n2, n3;
struct entry *list_pointer = &n1;
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n2;
n3.value = 300;
n3.next = (stuct entry *) 0;
while (list_pointer != (struct entry *)0) {
printf("%i\n", list_pointer->value);
list_pointer = list_pointer->next;
}
return 0;
}
I don't understand what the syntax (struct entry *) 0
, means here. In the book I am reading it says it is a null pointer. I tried looking online but I didn't know exactly what to type. The Google search results I got for 'NULL pointer' were different from what I expected.
Upvotes: 0
Views: 5712
Reputation: 41
A null pointer is initialized a pointer as invalid or it is marked as uninitalized. The NULL pointer is also available instead of the next pointer and thus also indicates the end of a list.
Upvotes: 0
Reputation: 67476
It does exactly the same job as NULL which is (void *)0 as defined in the C standard..
Upvotes: 1
Reputation: 9481
Null pointer is a pointer that points to memory address 0. Most system reserve this address so that no object will ever reside in there. This reservation allows to use it as blank address.
If you try to read or write from null pointer you will get runtime error which is sometimes called segmentation fault, or null pointer exception.
In your example the null pointer is used to indicate end of the list. So this condition (struct entry *) 0,
checks if you have reached end of the list and iteration should stop
Usually it considered better form to use constant NULL instead of literal value 0. This makes code more readable, and also covers very rare case when NULL pointer is not a 0
The cast (struct entry *)
is just to avoid compiler warning, because literal 0 is of type integer not a pointer. That's another reason to use constant NULL, because it is usually defined as (void*) 0
which compares nicely to any pointer value without a warning from compiler
Upvotes: 5
Reputation: 937
Any pointer type with the value 0 is called a null pointer. Here is the explanation from the C standard §6.3.2.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
Upvotes: 7