This is supposed to print 3,5,-1. I don't understand what is happening under-the-hood. What is happening when the function foo is called? I am having trouble understanding the last 4 lines in the function foo. I understand everything else.
Asked
Active
Viewed 48 times
-2
-
5Please post both the question, the code, what you _do_ understand and what exactly you are confused about. – Aasmund Eldhuset Oct 13 '15 at 01:48
-
Obviously the line `y++` increments the pointer, not the value where it points. You would need to make it `(*y)++`. In this exercise, they are showing the difference between pass by reference `&var` and pass by pointer `*var`. In passing a pointer, explicit dereference is needed. – alvits Oct 13 '15 at 02:20
-
"The last four lines"? You mean starting from `*y = z;`? – Beta Oct 13 '15 at 02:31
-
Oh you need explanation of the last 4 lines of `foo()`. The first line increments the local copy `z` by `2` giving it a new value `5`. The second line assigns to the memory pointed by `x` the difference by subtracting the value of local variable `z` from the value in the memory pointed by `y`. The next line increments the local pointer `y` by 1. As I have mentioned in my previous comment, you probably want to increment the value contained in the memory pointed by `y`. – alvits Oct 13 '15 at 02:38
-
[What are the barriers to understanding pointers and what can be done to overcome them?](http://stackoverflow.com/q/5727/995714) – phuclv Oct 13 '15 at 04:04
1 Answers
0
function essentially becomes
foo(&x, arr[0], 3)
z = z+2 // z=3+2=5
x = *y -z; // x=arr[0]-5=4-5=-1
*y = z; //arr[0]=5
notice a
is still 3
because it is passed by value. b
points to the start of the array which is 5
after the execution of the function. and c
is -1
because pass by reference.

夢のの夢
- 5,054
- 7
- 33
- 63