0

I have a C program

#include<stdio.h>

void f(const int* p)
{
  int j;
  p = &j;
  j = 10;
  printf("Inside function *p = %d\n",*p);
  *p = 5;
  printf("Inside function *p = %d\n",*p);
  j = 7;
  printf("Inside function *p = %d\n",*p);
}

int main()
{
  int i = 20, *q = &i;
  f(q);
}

Compilation of the program gives the error

Assignment of the read only location *p

at the line *p = 5;

Why is that the assignment j = 10; is valid and *p = 5; is an error.

Vinod
  • 4,138
  • 11
  • 49
  • 65
  • 3
    You declared `p` to be a `const int *p`. The `const` means you don't intend to change the value of `*p`. But you did, so got the error. `j` is declared as `int j`. It's not `const`, so you can change it. – lurker Mar 07 '14 at 03:56
  • @mbratch This could be the point, but djhaskin explains more clearly. – Vinod Mar 07 '14 at 04:03
  • [Changing value of const int using using pointer duplicate](http://stackoverflow.com/questions/20929551/changing-value-of-const-int-using-using-pointer?rq=1), [Const variable changed with pointer in C](http://stackoverflow.com/questions/9371892/const-variable-changed-with-pointer-in-c), [Confusion regarding modification of const variable using pointers](http://stackoverflow.com/questions/21372713/confusion-regarding-modification-of-const-variable-using-pointers?rq=1) –  Mar 07 '14 at 04:13

3 Answers3

5

const int *p means that you can't modify the integer that p is pointing to using p, as in *p = 5;. The integer it points to may not be a const int, which is why j = 10 works. This prevents coders from modifying integer being pointed to.

djhaskin987
  • 9,741
  • 4
  • 50
  • 86
2

const int* p mean you can not change the content in the address of p

which is you can not chanage *p

michaeltang
  • 2,850
  • 15
  • 18
0

const int mean , its value remain same until program ends so you can not change its value.

Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45