Why do I say int *p = NULL in the declaration, but p != NULL in the test, why not *p != NULL to match the declaration?
in c++, if we assign a pointer value to NULL
,why dont we check if *p!=NULL
and instead p!=NULL
?
I found this code in a tutorial.
int *p = NULL;
char *q = NULL;
// ...
if (p!=NULL) cout << *p;
开发者_StackOverflow中文版Thanks in advance
The *
is doing two different things. When you declare the variable, it means the variable is a pointer. When you use the variable, it means "dereference", that is take the value at the location the pointer is pointing to. Two totally different meanings.
Because p
is the pointer, and *p
is the object that it points to.
I think you are confused. The code from the tutorial is creating a pointer and initializing it to NULL
, then later it is testing if it is NULL
. The reason why you don't check if *p != NULL
is because that would be testing if what it points to is NULL
, and not test if the pointer itself is NULL
.
Of course you can choose to test *p
against any value you like provided it is a valid pointer... It all depends on what you want to do.
EDIT:
You didn't assign NULL
to *p
, you assigned it to p
. The statement int *p = NULL;
is the same as writing:
int *p;
p = NULL;
int *
is the type.
Basically, when you write: if(p != NULL)
you are simply testing if p
points to a place such that it is safe to use *p
.
The code is declaring a int pointer through the statement int *p = NULL
. Please note that these statements are equivalent:
int *p = NULL;
int* p = NULL;
And both of these mean that p is a pointer to an integer which further means that p holds the address of an integer. So, when the code later checks for
if(p != NULL)
it is basically checking that whether the address contained in this pointer is NULL or not. I hope it makes things clear.
Because p
is a pointer; it is a variable that holds a memory address of some object.
The code checks if the pointer is pointing to an object and, if it is, shows the value of that object on the screen.
if (p != NULL) // "if p is pointing to an object then ..."
{
cout << *p; // "show me the value of that object on the screen"
}
p
is the address of the object*p
is the value of the object, called dereferencing
精彩评论