-2
#include<stdio.h>
int main() 
{ 
int i = 11; 
int *p = &i; 
foo(&p); 
printf("%d ", *p);
} 
void foo(int *const *p) 
{ int j = 10;
*p = &j;
printf("%d ", **p);
} 

//it showed compile time error. Can anyone please explain

  • Of course there is an error and it is unrelated to `foo` but your `#include` line at the very least. – Eugene Sh. Jun 05 '19 at 21:09
  • 1
    *"//it showed compile time error."* What error? Compilers give non-trivial diagnostic output, debugging is easier when you read it. – dmckee --- ex-moderator kitten Jun 05 '19 at 21:11
  • You're actually lucky that your code doesn't build, because you would otherwise dereference an invalid pointer and have *undefined behavior*. See [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) for details. – Some programmer dude Jun 05 '19 at 21:19
  • Is your question as in the title, or rather about why the code does not compile? They appear to be two different and unrelated questions. The argument type `int *const *` _pointer-to-const-pointer-to-int_ takes some thinking about, but is valid. – Clifford Jun 05 '19 at 22:16
  • Initially " int *const * " seemed to be the reason of error. I want to know, why the code didn't compile? – Jaya Pandey Jun 06 '19 at 11:43

2 Answers2

4
int *const *p

p is a pointer to a constant pointer to int.

You can change p itself;
You cannot change *p;
You can change **p.

void foo(int *const *p) 
{ int j = 10;
*p = &j; // nope
printf("%d ", **p);
}
pmg
  • 106,608
  • 13
  • 126
  • 198
1

In your code you defined the method after calling it, so you should place it before main()