Home > Software design >  Im not sure why im getting this result out of my pointers exercise
Im not sure why im getting this result out of my pointers exercise

Time:11-22

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.

CodePudding user response:

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.

CodePudding user response:

The pointer ptr is initialized by the address of the variable var1.

ptr=&var1;

So using the expression *ptr is the same as using the expression var1 because dereferencing the pointer you get the variable var1.

Thus these expression statements

*ptr=var2;
var1=var1/ *ptr;

may be equivalently rewritten like

var1 = var2;
var1 = var1 / var1;

var2 was initially assigned with the integer constant 12

var2=12;

and the result value of the variable var1 will be equal to 1 independent on which value it has before assigning the result of the expression var1 / var1 (of course provided that.var1 was not equal to 0)

  • Related