Home > Mobile >  Why is 'a' displayed as 40 in ouput?
Why is 'a' displayed as 40 in ouput?

Time:12-11

int a;
int *p=&a;
a = 20;
*p = 40;
printf("%d",a);

Output: 40

Can anyone explain why the output is 40?

CodePudding user response:

Lets draw it out:

 ---       --- 
| p | --> | a |
 ---       --- 

That is, the variable p points to the variable a.

When you use *p you follow the pointer to get a.

So *p = 40 is equivalent to a = 40.

CodePudding user response:

In this code, the a variable is declared as an int, and it is initialized with the value 20. A pointer p is then declared, and it is initialized with the address of the a variable.

Next, the value of the a variable is modified by using the pointer p. The * operator is used to dereference the pointer, which means that it gives us the value stored at the address that the pointer points to. In this case, the pointer p points to the a variable, so when we dereference p and assign the value 40 to it, we are effectively assigning the value 40 to the a variable.

Since the value of the a variable was previously set to 40 using the pointer, the output of the printf statement is 40.

The output is 40 because the pointer is used to modify the value of the a variable, and the printf statement prints the modified value of a.

  •  Tags:  
  • c
  • Related