C 语言的 const 指针,指针的const有什么不同

Posted WenYao.Huang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C 语言的 const 指针,指针的const有什么不同相关的知识,希望对你有一定的参考价值。

Read it backwards (as driven by Clockwise/Spiral Rule)...

  • int* - pointer to int
  • int const * - pointer to const int
  • int * const - const pointer to int
  • int const * const - const pointer to const int

Now the first const can be on either side of the type so:

  • const int * == int const *
  • const int * const == int const * const

If you want to go really crazy you can do things like this:

  • int ** - pointer to pointer to int
  • int ** const - a const pointer to a pointer to an int
  • int * const * - a pointer to a const pointer to an int
  • int const ** - a pointer to a pointer to a const int
  • int * const * const - a const pointer to a const pointer to an int
  • ...

And to make sure we are clear on the meaning of const

const int* foo;
int *const bar; //note, you actually need to set the pointer 
                //here because you can‘t change it later ;)

foo is a variable pointer to a constant int. This lets you change what you point to but not the value that you point to. Most often this is seen with cstrings where you have a pointer to a const char. You may change which string you point to but you can‘t change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn‘t be changed.

bar is a const or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a T* const pointer unless you need to allow null pointers.

以上是关于C 语言的 const 指针,指针的const有什么不同的主要内容,如果未能解决你的问题,请参考以下文章

C语言 const 修饰指针

c语言中const 是啥意思,怎么用,啥时候用?

C语言 const与指针

如何利用指针改变const类型的值

[原创]c语言中const与指针的用法

指针与 const --- 指针常量与常量指针