Standard idiom for walking along a list in C
I am reading "The practice of programming" and it says that a standard loop for walking along a list in C is:
for (p=list;p != NULL;p=p->next)
...
My question is how does NULL work? I myself have used this in programs, but never paused to ponde开发者_开发百科r over how it works.
I suppose, NULL must be a standard macro defined in a very basic header file like stdio.h but what it is defined as? Is it?
#define MACRO 0
here how does 0 work when we compare a pointer to 0. This 0 could be a valid memory address 0, then how do we distinguish to say that we actually mean invalid address i.e. the pointer has a logical empty value?
Thanks,
The C FAQ has a whole section on NULL pointers. A short summary:
- the constant int value zero (
0
), in a context where the compiler knows a pointer is needed, is treated as the "null pointer": a pointer value known to not point at a valid memory address - this only applies to constants, not any integer values; for example, assigning zero to a variable, and then using that as a pointer, does not guarantee the value will be a null pointer
- the real address may or may not be zero; the compiler may translate it to another address
- several standard library headers define the macro
NULL
, either as a plain0
or cast into a pointer:((void *) 0)
(the C standard allows either)
It's defined as 0, yes. The thing is that 0 is not a valid memory address; computers are actually put together such that trying to access that address is an error.
Try running this program on your machine, if you want to insist that 0 is a legal address:
#import <stdio.h>
int main() {
int *p = 0;
printf("No read error: %d\n", *p);
*p = 1;
printf("No write error either\n");
}
精彩评论