c++指针数组中的Const限定符

const qualifier in c++ in array of pointers

本文关键字:Const 指针 数组 c++      更新时间:2023-10-16

假设我有一个指向整型的指针数组(即每个元素都是指向整型的指针)

int** ptrArray;

和我想要防止改变数组

的项所指向的整数

我需要把const放在哪里?

1. const int ** ptrArray
2. int const ** ptrArray
3. int *const*  ptrArray
4. int ** const ptrArray

这有什么规则吗?就像"第一个const保护数据","第二个const保护指针"等等?

const的位置背后有什么逻辑吗?把它放在哪里和它所保护的东西之间有联系吗?

这对我来说是一个非常令人困惑的问题,如果有人能给我任何指导或链接,我可以根据我想要保护的内容(万一我需要在三维数组中使用const)阅读更多关于如何以及在哪里使用const的信息,我将非常感激

这有什么规则吗?就像"第一个const保护数据","第二个const保护指针"等等?

是: const适用于左侧,除非那里没有任何内容,否则它适用于右侧

因此,

:

int const** ptrArray;

但是,作为特殊情况,这是等价的:

const int** ptrArray;

这意味着常见的模式const int x;实际上是 int const x;的伪装。

从变量开始读取修饰符

3. int *const*  ptrArray
  • ptrArray为变量。
  • *ptrArray表示指向某物的指针
  • const* ptrArray表示指向常量的指针
  • *const* ptrArray表示指向某物的常量指针

所以int *const* ptrArray;声明了一个指向(非常量)int的常量指针


要理解所有示例,您需要知道的最后一个技术细节是,int constconst int是表示同一类型的两种不同方式。

http://cdecl.org报告(或多或少,一个是无效的语法错误):

const int ** ptrArray:  declare ptrArray as pointer to pointer to const int
int const ** ptrArray:  declare ptrArray as pointer to pointer to const int
int * const * ptrArray: declare ptrArray as pointer to const pointer to int
int ** const ptrArray: declare ptrArray as const pointer to pointer to int

所以你要找的是:

const int ** ptrArray
int const ** ptrArray