【发布时间】:2019-01-04 20:53:17
【问题描述】:
我仍然对将const 放置在具有多个间接性的指针中的位置感到困惑。有人可以澄清一下吗?
例如现在我需要一个指向 const 指针的指针,这意味着这样一个变量 int **ppTargets 我可以将 int *pTargets 变量分配给它,例如:
int foo(int **ppTargets) {
int *pTargets = /* calculate here */;
*ppTargets = pTargets;
return 37; // just e.g.
}
上面的代码缺少const。所以在foo 中,我希望pTargets 指向常量内存并且在初始化后不可分配(这样就不能写,例如pTargets++),那就是int const *const pTargets = /* assigned once */。接下来我要声明ppTargetsppTargets本身可以赋值,但是*ppTargets只能读取。
换句话说,在我想要的调用者代码中:
int const* pTargets;
foo(&pTargets);
我尝试如下声明foo,但收到错误you cannot assign to a variable that is const:
int foo(int *const *const ppTargets)
【问题讨论】:
-
使用
typedef将您的简单类型构建为您真正想要使用的类型 -
你在自相矛盾:
So I want pTargets to point to constant memory and be const itself, that would be int const *const pTargets... 然后In the other words, in the calling code I want: int const* pTargets;那么,是哪一个?pTargets是否应该是 const ? -
@eerorika,换句话说,我想禁止分配给
pTargets和**pTargets,但不是*pTargets。我还没有看到矛盾,让我想想可能被误解的地方...... -
@SergeRogatch
I want to forbid assignment to pTargets与int const* pTargets矛盾,因为可以分配int const*。