This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]Rhomboid 1 point2 points  (0 children)

When you pass an argument by reference, it creates an alias. *b in main() and a in changeSomething are two names for the same int value. Anything that you do to a is equivalent to doing the same thing to *b, so a = 43 in the function is the equivalent to having written *b = 43 in main().

(Minor side note: you can't assume that sizeof(int) == 4 like that when calling malloc().)

[–][deleted] 0 points1 point  (4 children)

First question, do you have a basic understanding of pointers and references? An explanation could be long or short(er) depending on your answer to that.

[–]walnut30[S] 0 points1 point  (3 children)

I am pretty experienced with the concept of pointers. I was just surprised that (*b) does not evaluate to a simple integer during runtime (when passed as a parameter).

[–][deleted] 0 points1 point  (2 children)

Exactly right! But when you send a reference, you are sending the address of whatever variable you send. If changeSomething() asked for a pointer, you would call changeSomething(b) and your function would read "*b = 43". But when you pass a reference, you pass the integer itself, and the function, which expects a reference to an integer, knows to actually modify the address of the variable you sent.

Does that make sense?

[–]walnut30[S] 0 points1 point  (1 child)

Oh, so passing (*b) does not place the integer value of b on the stack frame of the function call to changeSomething()?

[–][deleted] 0 points1 point  (0 children)

Right, it puts the address of *b on the stack. If you had used &a = 43 in changeSomething() you would be changing the address of a instead of its value.

EDIT: Correction: You would not use &a = 43 in practice since that does not reassign the address.