NULL pointer in c programming

NULL pointer:

Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment.

Examples of NULL pointer:

1. int *ptr=(char *)0;
2. float *ptr=(float *)0;
3. char *ptr=(char *)0;
4. double *ptr=(double *)0;
5. char *ptr=’\0’;
6. int *ptr=NULL;

What is meaning of NULL?

NULL is macro constant which has been defined in the heard file stdio.h, alloc.h, mem.h, stddef.h and stdlib.h as
#define NULL 0

Examples:

What will be output of following c program?

#include <stdio.h>

int main(){
if(!NULL)
printf("I know preprocessor");
else
printf("I don't know preprocessor");

    return 0;
}

Output: I know preprocessor
Explanation:
!NULL = !0 = 1

In if condition any non zero number mean true.

What will be output of following c program?

#include <stdio.h>
int main(){

int i;
static int count;

for(i=NULL;i<=5;){
count++;
i+=2;
}

printf("%d",count);

return 0;
}

Output: 3

What will be output of following c program?

#include <stdio.h>

int main(){

#ifndef NULL
#define NULL 5
#endif

printf("%d",NULL+sizeof(NULL));

return 0;
}

Output: 2
Explanation:

NULL+sizeof(NULL)
=0+sizeoof(0)
=0+2 //size of int data type is two byte.

We cannot copy any thing in the NULL pointer.

Example:

What will be output of following c program?

#include <string.h>
#include <stdio.h>

int main(){

char *str=NULL;

strcpy(str,"c-pointer.blogspot.com");
printf("%s",str);

return 0;
}

Output: (null)






Generic pointer

Null pointer
Wild pointer
Dangling pointer
Near pointer
Far pointer
Graphics video memory
Text video memory
Huge pointer
Memory model in C
C tutorial

8 comments:

akash said...

MEANING OF
#define NULL 5
#define NULL

SOHAN said...

#include "stdio.h"

void main(){

int i;

static int count;

for(i=NULL;i<=5;){

count++;

i+=2;

}

printf("%d",count);


}


Output: 3




i want its explanation.................

please......................

golam kibria said...

the printf command is outside the loop
so out put 3 has no problem

Richa said...

in the last example could u pls explain wat actually is the meaning f output (null) ... wen i executed dis code i am getting segmentation fault.

Pradeep said...

This comment has been removed by the author.

Pradeep said...

@Richa,
add #include ... where NULL is defined...
u ll not get any error.... :)

Output: NULL means u cant copy into NULL pointer....
u r copying string into null pointer....
when u ll print tht pointer u ill get NULL as output....

:)

Satish Pawar said...

This comment has been removed by the author.

Satish Pawar said...

the example 2 is int *ptr=(char *)0;
however i think it should be int *ptr=(int *)0;
if it is not can anyone explian ?