Empty pointer nullin the C language, if a pointer does not point to any data, we call itNULL pointer, with
NULL
representation. For example:
int *p = NULL;
note Case-sensitive, NULL does not have any special meaning, just an ordinary identifier.
NULL is a macro definition, in
stdio.h
is defined as:
#define NULL ((void *) 0)
(void *)0
indicates that the value 0 is cast to
void *
type, outermost
( )
It is recommended to include macro definitions in our own macro definition to prevent ambiguity.
in summary, the value of P is 0. You can output the value of P:
- #include <stdio.h>
- int Main (){
- int *P = NULL;
- printf ("%d\ n", P);
- return 0 ;
- }
Operation Result:
0
we know that once a variable is defined, it allocates memory, and so is the pointer variable. For example:
int *p; It is not a null pointer
its value is random, is garbage value, if you accidentally use it, the runtime will generally cause a segment error, causing the program to exit, and even unknowingly modify the data.
p is defined, it must allocate 4 bytes (32-bit environment) space in memory, but its value is random, unlike
int
is initialized to 0, but it does point to a normal use of memory. When using P, it is the data of this memory, the lucky words can run normally, but most of the time this memory is not authorized to operate.
NULL causes P to point to address 0. Most systems use 0 as an unused address, so Wu will not destroy the data with P.
but not always, there are systems that use address 0, and null is defined as other values, so do not equate null with 0, and the following is unprofessional:
int *p = 0;
and should insist on writing as:
int *p = NULL;
Note the difference between null and NUL: null represents a null pointer and is a macro definition that can be used directly from your code. The NUL represents the character ' + ', the end-of-string flag, which is the No. 0 character in the ASCII code table. NUL is not defined in the C language, it is merely a salutation to ' + ' and cannot be used directly in the code.
void pointerThe C language also has a
void
pointer type, that is, you can define a pointer variable, but it does not indicate which type of data it points to. For example:
void *p = malloc (2);
allocates 2 bytes of space in memory, but is not sure what type of data it holds.
Note that void pointers are different from NULL pointers: null indicates that the pointer does not point to any data, is "empty", and the void pointer actually points to a block of memory, but does not know what type of data is in this memory.
C language null pointer null and void pointer