NULL --Null pointer constant
NULL is called a null pointer constant and is defined in "stddef.h" as "integer 0" or "integer 0 cast to (void *)".
Substituting NULL for pointer is called a null pointer. NULL can be assigned to any pointer type.
// Null pointer void * ptr = NULL; int32_t * int32_ptr = NULL; float * float_ptr = NULL;
NULL sample
This is a null sample.
Check memory allocation
In the sample below, NULL is returned if the memory allocation of the calloc function fails. Therefore, it can be used to check that memory is allocated.
#include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> int main (void) { // Pointer int32_t * nums = calloc (sizeof (int32_t), 10); // Pointer is not null if (nums! = NULL) { printf("Success\n"); } else { printf("Fail\n"); } free (nums); }
Output result
Success
Is there a child element in the node of the tree?
This is a sample of checking if a child element exists in a node of a tree.
#include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> struct myapp_node { struct myapp_node * first_child; struct myapp_node * last_child; };; int main (void) { // Parent node struct myapp_node * parent = calloc (sizeof (struct myapp_node), 1); // Child node struct myapp_node * first_child = calloc (sizeof (struct myapp_node), 1); // Assign to the first child of the parent node parent->first_child= first_child; if (parent->first_child! = NULL) { printf("Have First Child\n"); } if (parent->last_child== NULL) { printf("Don't Have Last Child\n"); } free (parent); free (first_child); }
Output result
Have First Child