const int* p
const适用于左侧内容,如果左侧没有,则适用于右侧内容。
const int* ptr1; // (1.) pointer to const int int const * ptr2; // (2.) same as 1. int* const ptr3; // (3.) const pointer to int const int* const ptr4; // (4.) const pointer to const int int const * const ptr4; // (5.) same as 4.
本文以const int* p为例。
int* p 只能指向变量,可读可写。
const int* p 只读指针,可以指向变量、常量等,只读。
int x{ 10 }, y{11}; const int cx{ 20 }, cy{ 21 }; int* p;//只能指向变量,可读可改。 const int* cp;//只读指针。可以指向常量、变量,但是只读,不可更改。 p = &x;//指针p指向地址x p = &y;//指向地址y //p = &cx;//错误, *p = 30;//改变地址y中的值 cp = &x; cp = &y; cp = &cx; cp = &cy; //*cp = 30;//错误