Reputation: 4352
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.
Upvotes: 0
Views: 172
Reputation: 5068
const int mean , its value remain same
until program ends so you can not change its value.
Upvotes: 0
Reputation: 10107
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.
Upvotes: 5
Reputation: 2898
const int* p mean you can not change the content in the address of p
which is you can not chanage *p
Upvotes: 2