I'm starting to study C++. I ran into a small confusion regarding pointers, specifically a NULL pointer. From my understanding when you declare a pointer and you set it to point to a value you can do the following:
int var = 10;
int *ptr;
ptr = &var;
*ptr = 20;
This would change the value of var to 20. But when you set a NULL pointer you do the following:
int *ptr = NULL;
Doesn't this mean you're assigning the value NULL to whatever variable ptr is pointing to not the address, because of the * operator? I thought a NULL pointer has a value (its address) as 0 so it points nowhere, from what I read. Would it make more sense to do this:
int *ptr;
ptr = NULL // or 0?
An explanation in layman terms would be appreciated, I'm still learning all the terms as I code and research so I'd love an explanation of any programming terms you use.
By saying
int *ptr = NULL;
you are saying "I am declaring an int-pointer calledptr
that I want to point to location0
(NULL
). That's all it's saying.Now, if you try to read or write to
ptr
you will get undefined behavior, which is generally a terrible place to be (much worse than just getting an error, because your program could start getting problems elsewhere and you won't know why). But generally,NULL
pointers are used when you want to signify that it should not be used and must be initialized.As David Schwartz said,
This is because the type of
ptr
is reallyint*
, a pointer to an integer. When declaring types,*
means pointer. It is only when using your pointers in expressions such as*ptr = 20
that the*
means "dereference".