-2

I am learning to code in C++ and came across null ptr. The book i read says that null pointers can not be dereferenced. That makes sense because there is nothing to dereference. But my question is that if null pointers can not be dereferenced then what is the point of having them in the context of defining a variable that you are not ready to initialize. Meaning if I am writing a program as follows:

int h =10;
int* h_pointer = &h;
int z = 123;
int* z_pointer = nullptr;

Why have the null pointer, if I can not change the value of later from null to &z.

Es Kay
  • 1
  • 4
    You can change the vaue of `z_pointer` to `&z` later, so "Why have the null pointer, if I can not change the value of later from null to &z." makes nonsense. – MikeCAT Feb 03 '21 at 18:21
  • 2
    _"can not be dereferenced"_ is not the same as cannot be modified. You can later assign `z_pointer = &z;`. – 001 Feb 03 '21 at 18:25
  • `h`, `h_pointer`, `z` and `z_pointer` are all _variables_ which means that you can change them when the program runs. You can let `z_pointer` point at any `int` and let other descisions made in the program dereference and even change the value of the `int` it's pointing at. `nullptr`s are also excellent to mark the end of _linked lists_. Here's a [toy program](https://godbolt.org/z/fnhavj) which demonstrates changing what an `int*` points at. – Ted Lyngmo Feb 03 '21 at 18:38
  • You don't really need to declare them together. You can put it closer to it's usage. (which actually is usually a good thing) – apple apple Feb 03 '21 at 19:14

1 Answers1

1

null pointers cannot be dereferenced

means that you cannot do

*z_pointer = z;

It is perfectly acceptable and expected to write to the pointer itself without dereferencing, for example

z_pointer = &z;
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720