   Assigning value through Pointer

+1 vote
78 views

5 = 6 --> its not valid. if yes then how come the below one is still valid?

int a = 10;
int *p = &a;
printf("%d", *p); // here *p will give 10, so its a constant
*p = 30; // here how we can assign a constant to constant ? posted Dec 4, 2014

+1 vote

In this case,

'p' is a pointer, initially you have make your pointer to point on address of variable 'a'.
now, if you want to access the value of 'a' through pointer then you have to use *p.
initially a = 10, and 'p' is pointing to a;
so now if you want to print the value of a, then you have to use either 'a' or *p.
now, you are doing *p = 30;
that means on the address of 'a' you are assigning value 30;
in Simple words, pointer can hold the address a and by pointer indirectly we can access that value.

i hope i have cleared you doubt. answer Dec 5, 2014

Step 1 : a is assigned as 10
Step 2: p is a int pointer type which is having the address of a
Step 3: assuming *p is a constant is a wrong interpretation, when we say x=10 then x is a variable which holds 10 as value.
Step 4: *p=30 saves the value at at the address where P is pointing, *p is not a constant. answer Dec 4, 2014
Correct.

Then how this printing the value?

printf("%d", *p);
%d is replaced with the value of *p
Similar Questions
``````printf ("%s %d %f\n", (*ptr+i).a, (*ptr+i).b, (*ptr+i).c);
[Error] invalid operands to binary + (have 'struct name' and 'int')
``````

where ptr is a pointer to the structure and allocated dynamic memory using malloc. Any suggestion would be helpful.