Why am I saying int * p = NULL in the declaration, but p! = NULL in the test, why not * p! = NULL match the declaration?

in C ++, if we assign a pointer value 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; 

Thank you in advance

+4
source share
5 answers

* performs two different things. When you declare a variable, it means that the variable is a pointer. When you use a variable, it means "dereferencing", that is, take the value in the place that the pointer points to. Two completely different meanings.

+15
source

Because p is the pointer, and *p is the object that it points to.

+11
source

I think you are confused. The code from the tutorial creates a pointer and initializes it to NULL , and then it tests if it is NULL . The reason you are not checking if *p != NULL is because it will be testing if what it points to is NULL and not checking if the pointer itself is NULL .

Of course, you can test *p for whatever value you like if it is a valid pointer ... It all depends on what you want to do.

EDIT:

You have not assigned NULL to *p , you have assigned it p . Statement int *p = NULL; same as entry:

 int *p; p = NULL; 

int * is a type.

Basically, when you write: if(p != NULL) , you just test if p points to such a place that it is safe to use *p .

+6
source

The code declares an int pointer through an int *p = NULL statement. Note that these statements are equivalent:

 int *p = NULL; int* p = NULL; 

And both of them mean that p is a pointer to an integer, which also means that p contains the address of the integer. So when the code later checks

 if(p != NULL) 

basically checks if the address contained in this pointer is NULL or not. Hope this is all clear.

+1
source

Because p is a pointer; this is a variable that contains the memory address of some object.

The code checks to see if the pointer points to an object and, if any, displays 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
0
source

Source: https://habr.com/ru/post/1343280/


All Articles