07-array-traversal.student

07-array-traversal.student - Last time: * Arrays (0-based,...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Last time: * Arrays (0-based, indexed, passed by reference) * Array pitfalls (no one checks "the edges") * Pointers (name locations in memory.) * Pointer syntax T *p; // p is a pointer-to-T T q; // q is of type T p = &q; // Let p "point to" q q = *p; // Let q be the value "pointed to by" p Today: * More on pointers as arguments * Pointer arithmetic * Pointers vs. references * Array-Pointer duality ++++++++++++++++++++++++++++++++++++++++++++++++++++ As with everything else, pointers can be arguments to functions. For example, suppose you want a function that adds one to an integer argument passed by reference. The prototype to that function is: void add_one(int *x); // MODIFIES: *x // EFFECTS: adds one to *x And you'd write it as: void add_one(int *x) { *x = *x + 1; } If you called this in our example environment: add_one(bar); The *variable* bar is passed *by value*, but bar itself happens to be a *pointer*. So, the usual function calling rules apply: create a new frame, evaluate the actual arguments in the calling environment, copy the values to the storage devoted to the formals, and execute. So, you'd get the following: +-------------------------+ | +----+ | | foo | 2 |<---------+---\ | +----+ | | | | +----+ | | | | bar | --------------/ | | +----+ | | +-------------------------+ |
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
| +----+ | | | x | ------------------/ | +----+ | +-------------------------+ x is a *copy* of the pointer bar. Since they both have the same value (that value is the address of foo), they both *point* to the same thing. When you execute the function, you get: +-------------------------+ | +----+ | | foo | 3 |<---------+---\ | +----+ | | | | +----+ | | | | bar | --------------/ | | +----+ | | +-------------------------+ | | +----+ | | | x | ------------------/ | +----+ | +-------------------------+ You can also call add_one without the "middleman" of bar, like so: add_one(&foo); Which says "take the address of foo, and pass it as the actual argument". What happens if you change the body of add_one to:
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/28/2010 for the course EECS 280 taught by Professor Noble during the Winter '08 term at University of Michigan.

Page1 / 6

07-array-traversal.student - Last time: * Arrays (0-based,...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online