/* Ferworn F06 Notes and (some bad) Examples of "Pass by Reference" Pass by Reference: The only way to change variables you got from outside a function through a parameter list, inside the function: Pointer: A pointer is a variable that is capable of storing the address of another variable of a certain type. A pointer is the device used by C to remember the address in memory where the actual value is stored. Declaring a pointer: To declare a pointer you need to put a '*' in front of the variable name and use a standard variable declaration. For example to declare an float pointer named bill use: float *bill; making a pointer point at something: To use a pointer it must point at the thing you want to actually modify. One way of doing this is to use the '&' or "address of" operator. if you had a float variable called sally and you wanted to make bill point at it you would use: bill = &sally; Manipulating the thing being pointed at: To actually work with the value being stored at the location being pointed at by the pointer you must do something called "dereferencing". You dereference or "work with the value stored at" using the '*' again. If you want to add one to the value stored in sally using bill the pointer you could do the following: *bill = *bill + 1; If you printed out the value of sally you would find it is one more than it was before you added one (in this rather strange way) to what bill points at. */ #include <stdio.h> void addone(int *); void stealvalue(int *); int main() { int jane = 10000; int jane_sister = 0; int *sam; sam = &jane; printf("%d\n",jane); addone(sam); printf("%d\n",jane); addone(&jane); printf("%d\n",jane); printf("Jane is worth: %d. Her sister is worth: %d\n", jane, jane_sister); stealvalue(&jane); printf("Jane is worth: %d. Her sister is worth: %d\n", jane, jane_sister); } void addone(int *incoming) { *incoming = *incoming + 1; } void stealvalue(int *incoming) { /* Never try this at home */ *(incoming + 1) = *incoming; *incoming = 0; } /* Output 10000 10001 10002 Jane is worth: 10002. Her sister is worth: 0 Jane is worth: 0. Her sister is worth: 10002 */