1 / 6

Pointer Perplexity?!?!?

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?.

tausiq
Download Presentation

Pointer Perplexity?!?!?

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Pointer Perplexity?!?!?

  2. 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

  3. 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.

  4. 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

  5. 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;

  6. 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)

More Related