C Library Macros - NULL
Description
C Library Macros NULL is the value of a null pointer constant.
NULLis a macro representing a null pointer constant. It is usually defined as((void*)0), representing a null pointer to memory address 0.- In C++,
NULLmay be defined as0or0Lso that it can be compared with the integer0for comparison.
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
- NA
Return Value
- NA
Usage
NULLis used to indicate that a pointer does not point to any valid object or address. For example, when dynamic memory allocation fails, it usually returnsNULL.NULLis also used to initialize pointer variables, indicating that they currently do not point to any valid address.
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
NULLis the standard way to represent a null pointer, avoiding direct use of0or(void*)0, to improve code readability and maintainability.- When comparing pointers, use
NULLinstead of directly using0. - In C++, you can use
nullptrinstead ofNULLto provide stronger type checking.
Related information
- In the C++11 standard, the
nullptrkeyword was introduced as a more type-safe null pointer constant. NULLThe definition of the macro may vary slightly depending on the compiler and standard library implementation, but its meaning and purpose are consistent.
C Standard Library -