top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Assigning value through Pointer

+1 vote
543 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 by sivanraj

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+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 by Chirag Gangdev
0 votes

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 by Salil Agrawal
Correct.

Then how this printing the value?

printf("%d", *p);
%d is replaced with the value of *p
Similar Questions
+4 votes
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.

Thanks in advance.

+1 vote

int arr[ ] = { 1, 2 };
p = arr; /* p is pointing to arr */

How pointer p will behave ?

+4 votes

What is the point of declaring Pointer of different types (eg. integer,float,char) as we all know pointer takes 4 bytes of space regardless which type of pointer it is and only contains address?

...