60 likes | 145 Views
Pointer Perplexity?!?!?. Why?. A function can only return one value using the return statement Thus, we use pointers to “return” more than one value to the calling function We also use pointers to “pass” arrays, particularly strings of characters. How?.
E N D
Why? • A function can only return one value using the return statement • Thus, we use pointers to “return” more than one value to the calling function • We also use pointers to “pass” arrays, particularly strings of characters
How? • By calling a function with the address of the data, rather than the value of data, the called function can modify the data in memory • This is called “pass by reference” as opposed to “pass by value” • The & operator in front of a variable name provides the location of the variable in memory, not the value of the variable.
Example #1 • The example below shows a function call in which the function can modify three items: one through the return value and the other two through memory • var1, var2, and var3 are variables in main() • &var1 is a pointer to the location of var1 in memory, i.e., a memory address var3 = my_func (&var1, &var2); // pass the addresses of var1 and var2
Example #1 (cont) • The arguments must be identified as pointers using * in the argument list • my_func can access the data using the pointers • read the data tmp_var = *var1_addr; • modify the data tmp_var = tmp_var + [...] • write new data into the memory location *var1_addr = tmp_var;
Example #1 (cont) intmy_func (int *var1_addr, int *var2_addr) { int var1_data; // declare local variable var1_data = *var1_addr; // read data at address var1_addr [...] // modify the data *var1_addr = var1_data; // write the new data into memory [...] return (var3_data); } • Key Points: • var1_addr is a local variable in my_func of type “integer pointer” • *var1_addr allows access to that address location for reading or writing • &var1_addr is the location of the pointer!!!(not something we ever use)