Just read this article, you can distinguish between pointer constants and constant pointers

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 *ptrit, 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 pessence is to tell the compiler that the variable of the pointer type is a constant.
Constant pointer: const int *por int const *pessentially tells the compiler that the pointer pvariable points is not possible through a pointer pto the modified value, i.e., for the pointer p, a variable it points *pis 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 ppost. 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 pmust be placed last, *representing pointers and constconstants. 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: * constso the whole is a int * const p
constant pointer: const *so the whole is int const * p, or constit can also be ahead of time:const int * p

Specific resolution:
pointer constant: constfollowed by one p, a pointer type variable, which stores the address of the variable, an unchangeable pvalue, that is, the pointer's point remains unchanged.
Constant pointer: The constnext one is a variable *pas mentioned above *p, so the value of this variable cannot pbe 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~

Guess you like

Origin blog.csdn.net/weixin_43900869/article/details/114284404