Pointers contain the memory address to a value instead of the value itself. To take the address of a variable, use
x := &a. To access the value at an address, we use
Before delving deeper, lets understand what is the meaning of passing by value as compared to passing by reference.
If we have a function that takes in an
f(x int) and if we have
j:=5, and we call
f(j), we first create a copy of
j with a value of
5 and then pass it to
f. Modifying the passed variable will not affect the original variable.
When we pass by reference, it means we pass the address of the variable, i.e.
f(&j). The address of a variable refers to the memory address where the variable lives.
In the above image, we allocate a value of 10 to
x and 12 to
y. Now, the system chooses a memory location where it will store
y. In this example, the system has chosen memory address
When we pass by reference, we will not pass
x, but rather the address of
x, which is
0 in this example. Now, at address
0, we hold the value
10. Hence, modifying the contents of an address will mean we modify what is stored there, and hence, the value of
x will be modified as well.
In the above example, we have two functions:
addTwo takes an
addOne takes the pointer to an
Testing with these two functions will show that the value of
x is modified when passed to
addOne as the function modifies the value stored at a particular memory address. In
addTwo however, we created a copy of
x and passed that copy, which means any changes made inside
addTwo has no impact on the original variable