-2

We know that in int *const p, where p is a constant pointer it means that address that p holds cannot changed but here in function foo we change the address.

How can it be possible?

int main(){
    int i = 10;
    int *p = &i;
    foo(&p);
    printf("%d ", *p);
    printf("%d ", *p);
}
void foo(int **const p){
    int j = 11;
    *p = &j;
    printf("%d ", **p);
}
MikeKeepsOnShine
  • 1,730
  • 4
  • 23
  • 35

2 Answers2

2

int **const p means p is constant.

So following are not allowed

p++; // Bad
p += 10; // Bad
p = newp; // Bad

But following are fine:

if(p) *p = some_p;
if(p && *p) **p = some_int;

If you want *p should not be re-assigned, use the following

int * const *p;

If you want neither p nor *p should be changeable, use:

int * const * const p;

And following will make all p, *p and **p read-only

  const int *const *const p;
//  1          2      3

1: **p is constant
2: *p is constant
3: p is constant

Use 1 or 2 or 3 or any combination as per your requirement.

cdecl page: How to read complex declarations like int ** const p and const int *const *const p

Related: c - what does this 2 const mean?

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
0

In your case, const is applied on p itself, not on * p or ** p. In other words, you can change *p and **p, but you cannot change p.

FWIW, try changing the value of p and see.

See it LIVE

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    prog.c: In function 'foo': prog.c:17:7: error: assignment of read-only parameter 'p' p = &j; – Tas Jul 15 '15 at 07:26
  • 1
    Oh sorry, I thought you were demonstrating only what values could be changed, mb. – Tas Jul 15 '15 at 07:27