Download presentation
Presentation is loading. Please wait.
1
ENERGY 211 / CME 211 Lecture 10 October 13, 2008
2
Pointers A pointer to an object is a variable whose value is the object's address To declare a pointer: type *var-name; To access the underlying object's value, use the dereferencing operator * Use the address operator & to obtain an object's address, whose type is a pointer to the object's type To output address, can use <<: int x; int *p = &x; cout << p;
3
Pointers as Arguments C++ inherited pointers from C
In C, values of variables passed to functions cannot be changed How can functions change values of arguments? Solution: pass address of the actual parameter; function accepts pointer Inside function, dereference pointer using * to access value (and change it!)
4
Arrays and Pointers A pointer can point to an element of an array: int x[4]; int *p = &x[0]; Can add to a pointer to access another element: value of *(p+1) is x[1] Pointer arithmetic accounts for size of each element, so use the right types! If a function accepts a pointer as an argument, can pass an array of the same type
5
Dynamic Instances Variables declared inside a function go away when the function exits Arrays must be declared to have a fixed size, known at compile time Can allocate memory dynamically Form: type *name = new type; Array: type *name = new type[expr]; where expr is a positive integer Can use any constructor for type
6
Dynamic Instances, cont'd
A pointer/array created using new can be used like any other pointer/array If you allocate memory, you must de-allocate when you're done Form: delete ptr;, where ptr was previously allocated using new Failure to do so causes a memory leak Form for array: delete [] name; Can't delete pointer more than once!
7
NULL Pointers A NULL pointer is a pointer that does not actually point to any object Its value, in a sense, is zero Can always delete a NULL pointer Common uses: Initializing pointers Testing whether a pointer is usable Before you dereference a pointer, make sure it's not NULL or your program will crash!
8
C++ Smart Pointers C pointers are prone to misuse
C++ adds a smart pointer, a "wrapper" variable that contains a C pointer When wrapper is de-allocated automatically, like any other variable, pointer inside is deleted Form of declaration (T is a type): std::auto_ptr<T> name(new T); Can dereference like a C pointer
9
Iterators as Pointers Recall that iterators allow access to elements of a sequence such as a vector or string You can dereference an iterator to access the underlying element Example: *(s.begin()) is first character of string s Pointer arithmetic is valid with random-access iterators: *(s.begin()+1) is second character of string s
10
Next Time More on pointers! Improving efficiency using pointers
Matrix allocation strategies
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.