I’ve been asked to write what this codes does:
int main()
{
int var1,var2, *ptr;
ptr=&var1;
var2=12;
*ptr=var2;
var1=var1/ *ptr;
printf("%d %d", var1,var2);
}
Now my question is what does this means. At first ptr stores the address of var1. Then var2 is defined as 12. the next step idk what it means and so with the last one. I finally i get printed 1 and 12. Not sure why.
What i understood is that 12 is stored in ptr aswell. So as ptr has var1 address, var1 gets a value of 12 too. and so the finall step would be var1=12/12. And thats why i get 1 and 12 in my printf. This is just what i understood but i dont really get it and im not sure if its correct. Btw ty for undesrtanding.
>Solution :
ptr=&var1;
&var1 is the address of the object var1. ptr = &var1 stores the address in the object ptr.
var2 = 12;
This stores 12 in the object var2.
*ptr = var2;
This stores the value of var2 in the object *ptr. Since 12 is stored in var2, it stores 12 in the object *ptr. Since the value of ptr is the address of var1, *ptr is var1. So *ptr = var2 stores 12 in the object var1.
var1 = var1 / *ptr;
*ptr is the object that ptr points to, which is var1. So var1 / *ptr divides the value of the numerator, var1, by the value of the denominator, *ptr, which is also var1. Both the numerator and the denominator have the value 12, so var1 / *ptr is 1. Then var1 = var1 / *ptr stores 1 in the object var1.
printf("%d %d", var1,var2);
This prints the values of var1 and var2, converted to decimal. Per the above, var1 contains 1 and var2 contains 12, so “1 12” is printed.