Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Im not sure why im getting this result out of my pointers exercise

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading