char* const 及char const * 还有const char*的区别

如题,这三者的区别和含义是?

阅读 3.3k
3 个回答

在阅读和const相关的指针时,可以记一下这个规则:左数右指
意思是:当const出现在*号左侧时,指针指向的数据不可改变;当const出现在*号右侧时,指针指向不可改变(不可改变的意思是不能通过当前指针直接进行改变)。

char* const str = "str1";        // const位于*右侧,表示str这个指针不可改变
// str = "change";               // assignment of read-only variable 'str'
    
const char* str1 = "str1";       // const位于*左侧,表示str指向的字符串不可改变
//str1[3] = '2';                 // assignment of read-only location '*(str1+3)'
str1 = "str3";                   // ok,str1可以指向其他字符串

char const* 和 const char*效果一样。

stackoverflow上有一模一样的问题,我就复制粘贴了

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

// const 修饰的是 p0
char *const p0; // p0 是常量,不可修改。*p0 是变量,可修改。

// const 修饰的是 *p1 和 *p2
const char *p1; // p1 是变量,可修改。*p1 是常量,不可修改。
char const *p2; // 同上。

// 第一个 const 修饰的是 *p3
// 第二个 const 修饰的是 p3
const char *const p3; // p3 和 *p3 都是常量,不可修改。
char const *const p4; // 同上。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题