Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Macros – NULL

C Library Macros - NULL

C Standard Library - <stddef.h> C Standard Library -

Description

C Library Macros NULL is the value of a null pointer constant.

Declaration

The following is the declaration of the NULL macro, which depends on the compiler.



#define NULL ((char *)0)



或



#define NULL 0L



或



#define NULL 0

Parameters

Return Value

Usage

Example

The following example demonstrates the use of the NULL macro.

Example 1

#include

#include

int

main

(

)

{

   FILE

fp

;

   fp

=

fopen

(

"file.txt"

,

"r"

)

;

   

if

(

fp

!=

NULL

)

   

{

     

printf

(

"Successfully opened file file.txt\n"

)

;

     

fclose

(

fp

)

;

   

}

   fp

=

fopen

(

"nofile.txt"

,

"r"

)

;

   

if

(

fp

==

NULL

)

   

{

     

printf

(

"Cannot open file nofile.txt\n"

)

;

   

}

   

   

return

(

0

)

;

}

Suppose the file file.txt exists, but nofile.txt does not exist. Let's compile and run the above program, which produces the following result:



成功打开文件 file.txt

不能打开文件 nofile.txt

Dynamic memory allocation:

Example

#include

#include

int

main

(

)

{

   

int

ptr

=

(

int

)

malloc

(

sizeof

(

int

)

10

)

;

   

if

(

ptr

==

NULL

)

{

       

printf

(

"Memory allocation failed\n"

)

;

       

return

1

;

   

}

   

// Use the allocated memory

   

for

(

int

i

=

0

;

i

<

10

;

i

++

)

{

        ptr

[

i

]

=

i

;

   

}

   

// Free the allocated memory

   

free

(

ptr

)

;

    ptr

=

NULL

;

// Set the pointer to NULL

   

return

0

;

}

Function arguments:

Example

#include

#include

void

printString

(

const

char

str

)

{

   

if

(

str

==

NULL

)

{

       

printf

(

"String is NULL\n"

)

;

   

}

else

{

       

printf

(

"String: %s\n"

,

str

)

;

   

}

}

int

main

(

)

{

   

char

string1

=

"Hello, World!"

;

   

char

string2

=

NULL

;

    printString

(

string1

)

;

// Output: String: Hello, World!

    printString

(

string2

)

;

// Output: String is NULL

   

return

0

;

}

Notes

Related information

C Standard Library - <stddef.h> C Standard Library -