指针无法更改为无法写入的指针?

时间:2015-02-05 22:26:40

标签: c++ c

如何声明这样的指针?

我应该把两个const放在哪里?

我认为这在C和C ++中是相同的。

3 个答案:

答案 0 :(得分:1)

以下是const /非 - const的四种变体,涉及指针及其指向的对象:

int i1 = 10;
const int i2 = 20;
int i3 = 30;
const int i4 = 40;

int* p1 = &i1;              // You can change p1 and *p1
*p1 = 25;                   // OK
p1 = &i3;                   // OK

const int* p2 = &i2;        // You can change p2 but not *p2
*p2 = 25;                   // Not OK
p2 = &i4;                   // OK

int* const p3 = &i1;        // You can not change p3 but you can change *p3
*p3 = 25;                   // OK
p3 = &i3;                   // Not OK

const int* const p4 = &i2;  // You can change neither p4 nor *p4
*p4 = 25;                   // Not OK
p4 = &i4;                   // Not OK

答案 1 :(得分:0)

const int * const ptr将有效。

最左边的const适用于int(指针对象)而另一个const适用于其左边的*,即指针。

int main()
{
  int i = 42;
  int b = 0;
  const int *const ptr = &i;

  ptr = &b; // doesn't compile
  *ptr = 1; // dito
}

答案 2 :(得分:0)

typedef const int *pointer_that_cannot_be_written_through;
typedef pointer_that_cannot_be_written_through *const unwriteable_pointer;
int a;
pointer_that_cannot_be_written_through b = &a;
unwriteable_pointer p = &b, q = &b;
p = q;    // ERROR
*p = *q;  // FINE
**p = **q // ERROR

事实上,p的类型为const int **const