Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I say int *p = NULL in the declaration, but p != NULL in the test, why not *p != NULL to match the declaration?

Tags:

c++

pointers

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;

Thanks in advance

like image 402
Frustrated Coder Avatar asked Mar 11 '11 04:03

Frustrated Coder


1 Answers

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.

like image 84
Mark Ransom Avatar answered Oct 20 '22 14:10

Mark Ransom