simran dhamija simran dhamija - 13 days ago 4
C Question

what does *p contain?

As per multiple sources, a pointer

p
points to a value when it is dereferenced. Thus, we may say that a pointer contains an address as it's value, and when the dereference operator (
*
) is used, the value at the address is returned.

A pointer may be assigned a value as follows:

int a = 90;
int *p = &a;


if we assign a pointer it's value as follows:

int *p;
*p = 60;


60 is alloted to
p
and causes undefined behavior upon dereferencing since 60 is not a valid address. (As per the answer to this question).

However, for the following code:

int a = 90;
int *p = &a;

printf ("p is %d \n",*p);
printf ("a is %d \n", a);
printf ("address is %p \n",p);

*p = 100;

printf ("p is %d \n",*p);
printf ("a is %d \n", a);
printf ("address is %p \n",p);


The following output is recieved :


p is 90

a is 90

address is 0028FED8

p is 100

a is 100
address is 0028FED8


ie, the expression
*p = 100
changes the value at
a
, and not the value contained by
p
.

HOW ??????

Answer

*p = &a doesn't even compile. p is a pointer to int. It currently has an undefined value, therefore assigning anything to *p is undefined behaviour and would most likely crash. However, even if p did point to an int, you could only assign an int to *p, &a is a pointer to int, not an int, so this doesn't compile.

In your second example, *p = 60, the value of p is undefined, so you are trying to store 60 to an undefined location in memory. Instant crash. p isn't modified by this, so your explanation is wrong. p is not set to 60. You can't set p to an int. You can only set it to a pointer to int.

Correct:

p = &a; 
*p = 60;