How do I check if a pointer is null in C?
I check if a pointer is null in C:
code:
#include <stdio.h>
int main()
{
int *ptr=NULL;
if(ptr==NULL)
printf("Yes");
else
printf("No");
return 0;
}
Null pointers are evaluated as false
when they are used in logical expressions. Thus, we can put a given pointer in the if
statement condition to check if it’s null.
Best way I do:
say the pointer in question is of type void *.
- printf(“address of foo: %p\n”, (void *)foo);
This will print the memory location of the void * variable foo or nil if NULL. Of course, you could always use the old fashion if check:
- if (NULL == bar)
- {
- // do something
- }
From the top:
#ifndef NULL
#define NULL (*)(0)
#endif
/**********************************/
/* we just have set a value for a */
/* NULL pointer. From ancient times */
/* this points to physical and or */
/* logical address 0 *************/
/*********************************/
/*********************************/
/* An example how to test for a */
/* NULL pointer follows: */
/* declare a pointer variable */
*int pointer;
pointer = NULL; /* set this pointer to NULL */
/****************************/
/* do the test now */
if(pointer==NULL)
printf(“NULL pointer found./n/r");
/* print out error message */
/* please excuse the formatting */
/* escape coding ----- the editor that */
/* I'm using is getting in the way */
/* of writing decent code for this example */
/*******************************************/
C programmers can point the compiler dependencies in this code and I quite agree that they are obvious, painfully so. I hope that the code is understandable, folks.
Simplest and most straightforward:
- if ( !p )
- // p is null
The null pointer constant (NULL
) is always zero-valued, so !p
is the same as p == NULL
.
int * p;
…
if (p==0) // is NULL
I always think simply if(p != NULL){..}
will do the job. But after reading this Stack Overflow question, it seems not.
So what's the canonical way to check for NULL pointers after absorbing all discussion in that question which says NULL pointers can have non-zero value?