我总是搞砸如何正确使用const int*、const int*const和int const*。有没有一套规则来定义你能做什么和不能做什么?

我想知道在赋值、传递给函数等方面的所有注意事项。


当前回答

简单助记符:

类型指针<-*->指针对象名称


我喜欢把int*I看作是声明“I的解引用是int”;在这个意义上,constint*i表示“i的deref是constint”,而int*consti表示“consti的derref是int”。

(像这样思考的一个危险是,它可能会导致人们倾向于int const*i风格的声明,而人们可能会讨厌/拒绝这种声明)

其他回答

两边带有int的常量将使指针指向常量int:

const int *ptr=&i;

or:

int const *ptr=&i;

*后的const将使常量指针指向int:

int *const ptr=&i;

在这种情况下,所有这些都是指向常量整数的指针,但没有一个是常量指针:

 const int *ptr1=&i, *ptr2=&j;

在这种情况下,所有指针都指向常量整数,ptr2是指向常量整数的常量指针。但ptr1不是常量指针:

int const *ptr1=&i, *const ptr2=&j;

我在下面画了一张图片来解释这一点,也许会有所帮助。

int const v和const int v是相同的。

就像每个人都指出的那样:

常量X*p、X*constp和常量X*const p之间有什么区别?

必须读取指针声明从右到左。const X*p表示“p指向常量的X”:X对象不能通过p更改。X*const p表示“p是指向非常量X的常量指针”:不能更改指针p本身,但可以通过p更改X对象。const X*const p表示“p是指向常量X的常量指针”:不能更改指针p本身,也不能通过p更改X对象。

一般规则是const关键字应用于它前面的内容。异常,起始常量适用于以下内容。

constint*与intconst*相同,表示“指向常量int的指针”。const int*const与int const*const相同,表示“指向常量int的常量指针”。

编辑:对于该做的和不该做的,如果这个答案还不够,你能更准确地说出你想要什么吗?

为了C遵循其他解释的完整性,对C++不确定。

pp-指针到指针p-指针数据-在示例x中指出的内容粗体-只读变量

指针

p数据-int*p;p数据-int常量*p;p数据-int*const p;p数据-int const*const p;

指向指针的指针

pp p数据-int**pp;pp p数据-int**const pp;pp p数据-int*const*pp;pp p数据-int常量**pp;pp p数据-int*const*const pp;pp p数据-int const**const pp;pp p数据-int const*const*pp;pp p数据-int常量*常量*常量pp;

// Example 1
int x;
x = 10;
int *p = NULL;
p = &x;
int **pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 2
int x;
x = 10;
int *p = NULL;
p = &x;
int ** const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

// Example 3
int x;
x = 10;
int * const p = &x; // Definition must happen during declaration
int * const *pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 4
int const x = 10; // Definition must happen during declaration
int const * p = NULL;
p = &x;
int const **pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 5
int x;
x = 10;
int * const p = &x; // Definition must happen during declaration
int * const * const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

// Example 6
int const x = 10; // Definition must happen during declaration
int const *p = NULL;
p = &x;
int const ** const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

// Example 7
int const x = 10; // Definition must happen during declaration
int const * const p = &x; // Definition must happen during declaration
int const * const *pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 8
int const x = 10; // Definition must happen during declaration
int const * const p = &x; // Definition must happen during declaration
int const * const * const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

N级取消引用

继续前进,但愿人类将你逐出教会。

int x = 10;
int *p = &x;
int **pp = &p;
int ***ppp = &pp;
int ****pppp = &ppp;

printf("%d \n", ****pppp);