When contacting pointer constants and constant pointers, I still get confused after learning it many times. I suddenly understand this a little bit by accident, so I can record it.
Pre-knowledge:
What we are more complaining about is *
that this symbol must be added to the pointer when it is defined , as follows:
int a = 10;
int *ptr = &a;
When we want to modify the value of the variable pointed to by the pointer, we do this:
*ptr = 20;
This is not the same as when we defined it.
At the same time, when we want to modify the pointing of the pointer, we do this:
int b = 30;
ptr = &b;
Essentially a pointer is a pointer type variable that stores an address symbol.
So when you use *ptr
it, you actually call the object it points to, usually called dereferencing.
So we just need to tell ourselves that the definition of pointers is special and *
cannot be distinguished from ordinary variables without using them. The definition of the pointer can be used specially, and the rest can be understood normally.
When studying the part of pointer constants and constant pointers, I often confuse it, and even after reading it many times, I still can’t remember. Here is a better understanding method that I personally think is better.
Definition:
Pointer constant: The int * const p
essence is to tell the compiler that the variable of the pointer type is a constant.
Constant pointer: const int *p
or int const *p
essentially tells the compiler that the pointer p
variable points is not possible through a pointer p
to the modified value, i.e., for the pointer p
, a variable it points *p
is a constant.
Writing method: When
giving these two nouns, we only need to write out the form first, and then see *
if it matches with the p
post. Let us not consider at the time of writing specifically what the basic data type of pointer, then there are only three terms: const
, *
, p
.
Which p
must be placed last, *
representing pointers and const
constants. It can be judged by writing according to the expression order of the nouns, and then adding the basic data type at the end.
Pointer constant: * const
so the whole is a int * const p
constant pointer: const *
so the whole is int const * p
, or const
it can also be ahead of time:const int * p
Specific resolution:
pointer constant: const
followed by one p
, a pointer type variable, which stores the address of the variable, an unchangeable p
value, that is, the pointer's point remains unchanged.
Constant pointer: The const
next one is a variable *p
as mentioned above *p
, so the value of this variable cannot p
be changed , that is, the specific value of the variable pointed to by the pointer cannot be changed by dereference .
So if you can’t distinguish between them in the future, you can do this~
Write to yourself who can't distinguish between the two in the future~