×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

NULL pointer in C

Learn: What is the NULL pointer in C language? When NULL pointer requires and what is the value of a NULL Macro?

As we have discussed in chapter "Pointers Declarations in C programming language" that a pointer variable stores the address of another variable. But sometimes if we do not want to assign the address in a pointer variable i.e. if we need a pointer that should not point anything. In such cases, we need a NULL pointer.

What is a NULL pointer?

NULL is a predefined Macro, and its value is 0 (since 0 is not a valid memory address, thus we can consider that NULL can be used for nothing or no address).

So, NULL pointer is a pointer variable that is assigned with NULL Macro.

Consider the following declarations

int *ptr=NULL;

OR

int *ptr;

In the given statement ptr is an integer pointer which is being initialized with NULL, thus ptr will be considered as NULL pointer.

Consider the program which is printing the value of NULL Macro and Null pointer

#include <stdio.h>

int main()
{
	int *ptr;	/*integer pointer declaration*/
	ptr=NULL;	/*Assigning the NULL to pointer*/
	
	/*printing the value of NULL Macro*/
	printf("Value of NULL Macro: %d\n",NULL);

	/*printing the value of NULL Pointer*/
	printf("Value of NULL pointer: %p\n",ptr);	
	
	return 0;
}

Output

Value of NULL Macro: 0
Value of NULL pointer: (nil)

Output clears that value of NULL Macro is 0 and the value of NULL pointer is (nil) that means pointer ptr does not has any valid memory address.

Here we are using %p to print the value of ptr
Why?
Because, ptr is a pointer variable and it stores memory address, format specifier %p is used to print memory addresses in Hexadecimal format.


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.