Question:
please explain this basic C program (involves pointer)?
IHave
2012-03-07 19:13:39 UTC
i know the program outputs -31. How would this be determined by hand. please show steps if possible. thanks.

#include

void func(float *px, float *py)
{
*px = 3 + 2 * *px;
*py = *py - 21;

}

int main()
{
float x=0, y=4, z= 1;
int i;

func(&x, &y);
func(&y, &z);

printf("%f\n",y);
return 0;
}
Three answers:
McFate
2012-03-07 19:17:48 UTC
*px = 3 + 2 * *px doubles the first variable's value and adds 3, overwriting the first variable with that.

*py = *py - 21 subtracts 21 from the second variable's value, overwriting the second.



Initially, x,y,z = 0,4,1.



func( &x, &y) changes

x from 0 to 3 (2*0 + 3 -> 3), and

y from 4 to -17 (4 - 21 -> -17)



func( &y, &z) changes

y from -17 to -31 (2*(-17) + 3 -> -31, and

z from 1 to -20 (1 - 21 -> -20)



Then you print y, which is now -31.



@M
Lakers Too Good
2012-03-07 19:19:39 UTC
x = 0, y = 4, z = 1 //initial



func(&x, &y): //first func call

x = 3 + 2*0 = 3

y = 4-21 = -17



func(&y, &z): //second func call

y = 3 + 2*-17 = -31

z = 1-17 = -16



print(y) //prints -31, because y is now -31
barsegyan
2016-10-21 06:01:38 UTC
If this application is giving you mistakes please do this once which run void InputEmployeeRecord(worker *ptrEmployee); it will be void InputEmployeeRecord(worker &ptrEmployee); else specify more desirable what you want


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...