I am new to C++ and am following the book "Programming Principles and Practices using C++". I came across something that I could not understand completely. Hopefully someone can help me understand this.
Why is this invalid?
int* p = nullptr;
*p = 7;
I am new to C++ and am following the book "Programming Principles and Practices using C++". I came across something that I could not understand completely. Hopefully someone can help me understand this.
Why is this invalid?
int* p = nullptr;
*p = 7;
 
    
     
    
    nullptr is a special address. In particular, nothing can ever be stored there. Attempting to dereference a null pointer is undefined behavior (in fact, it's the first example on that list).
Now, to be clear, what you're doing is not reassigning a pointer itself. Given this code:
int* p = nullptr;
*p = 7;
This is dereferencing the pointer and then reassigning the value of the thing that the pointer is pointing at. And since nullptr does not point at anything, dereferencing a nullptr is undefined behavior, so the assignment is invalid.
Now, given this code:
int q = 42;
int* p = nullptr;
p = &q;
This is reassigning the pointer itself. This is perfectly valid. We started with a pointer that is pointing to nothing, and then tell it to point to something else (in this case, a local variable). Notice that I don't put a * when I assign to p in this example. I never dereference a nullptr, so I never hit that particular problem.
 
    
    