80 likes | 171 Views
Pointer Perplexity?!?!?. What?. All variables “live” in memory – either on the stack (e.g., auto locals) or at fixed locations (e.g., globals and static locals)
E N D
What? • All variables “live” in memory – either on the stack (e.g., auto locals) or at fixed locations (e.g., globals and static locals) • A pointer is nothing more than a special type of variable that can only take on the value of a memory address or location, not the data in that location • The compiler also needs to know what type of data is stored at that memory address, e.g., char, unsigned short
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. Providing the address as an argument enables the function to modify the data stored there • 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 address operator (&) in front of a variable name provides the location of the variable in memory, not the value of the variable, e.g., &my_var
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. (see next slide) • my_func can then 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 (Complete) 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)
Pointer Error • You can also declare a pointer as a local variable, e.g., int*my_int_ptr; • This declares a pointer to an integer variable • However, the pointer is not initialized and can’t be used until a valid address is assigned to it., e.g. my_int_ptr = &my_int_var;