Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.

Similar presentations


Presentation on theme: "CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object."— Presentation transcript:

1 CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object itself –Also known as “aliasing” Two ways to do this –Indirectly, via a pointer Gives the address (in memory) of the object Requires the user to do extra work: dereferencing –Directly, via a reference Acts as an alias for the object User interacts with reference as if it were the object itself

2 CSE 332: C++ pointers, arrays, and references Untangling Operator Syntax SymbolUsed in a declaration Used in a definition unary & (ampersand) reference int i; int &r = i; address-of p = &i; unary * (star) pointer int * p; dereference (what’s pointed to) *p = 7; -> (arrow) member access via pointer cp->add(3);. (dot) member access (same syntax for either reference or object) c.add(3);

3 CSE 332: C++ pointers, arrays, and references What’s a Pointer? A variable holding an address –Of what it “points to” in memory Can be untyped void * v; // can point to any type However, usually they’re typed –Checked by compiler –Can only be assigned addresses of variables of the type to which it can point int * p; // can only point to int Addresses: garbage, something, nothing –When created: int * p = i; vs. int * q; q = 0; // now it points to nothing p = NULL; // bad idea, not portable 0x7fffdad0 7 int i int * p 3 const int j 7 int k

4 CSE 332: C++ pointers, arrays, and references What’s a Reference? A variable holding an address –Of what it “refers to” in memory But with a nicer interface –An alias to the object –Hides indirection from programmer Must be typed –Checked by compiler –Again can only refer to the type to which it can point int &r = i; // can only refer to int Must always refer to something –Must be initialized, cannot be changed 0x7fffdad0 7 int i int &r

5 CSE 332: C++ pointers, arrays, and references Aliasing and Pointers int main(int, char *[]) { int i = 0; int j = 1; int *p = &i; int *q = &i; *q = 6; // i is now 6, j is still 1 cout << i << “ ” << j; } Distinct variables alias different memory locations –E.g., i and j An object and all the pointers to it (when dereferenced) alias the same location –E.g., i, *p, and *q Assigning a new value to i, *p or *q changes value seen through the others But does not change value seen through j 0xefffdad0 6 int i int *p 1 int j 0xefffdad0 int *q

6 CSE 332: C++ pointers, arrays, and references Location and Value Comparisons Pointers may be compared for equality –Same as comparing addresses of what pointers point to (memory locations: l-values) Contents of what pointers point to may be compared, too (r-values) First implies second, not other way around p == q&*p == &*q *p == *q 0xefffdad0 5 int i int *p 5 int j 0xefffdbd0 int *q

7 CSE 332: C++ pointers, arrays, and references Const Pointers and Pointers to Const Types int main (int, char *[]) { const int i = 0; int j = 1; int k = 2; // pointer to int int * w = &j; // const pointer to int int * const x = &k; // pointer to const int const int * y = &i; // const pointer to const int const int * const z = &j; } Make promises via the const keyword in pointer declaration: –not to change pointer itself –not to change value it aliases –can also promise neither/both Read declarations right to left In this example, can change –w and what it points to –what x points to but not x –y but not what it points to –neither z nor what it points to A pointer to a non-const type cannot point to a const variable –w and x can’t point to i

8 CSE 332: C++ pointers, arrays, and references Aliasing and References int main(int, char *[]) { int i = 0; int j = 1; int &r = i; int &s = i; r = 8; // i is now 8, j is still 1 cout << i << “ ” << j; } An object and all the references to it alias the same location –E.g., i, r, and s Assigning a new value to i, r or s changes value seen through the others But does not change value seen through j 0xefffdad0 8 int i int &r 1 int j 0xefffdad0 int &s

9 CSE 332: C++ pointers, arrays, and references Const References int main (int, char *[]) { const int i = 0; int j = 1; // non-const reference // r can’t refer to i int &r = j; // this is ok, though const int &s = i; const int &t = j; } Remember: references must refer to something –Can’t be 0 (or NULL) –Except through bad tricks like int *p = 0; int & r = *p; Also, once initialized, references cannot be changed –E.g., can’t redirect t to i –In Java, can re-assign references –In C++, you cannot Const reference –Promise not to change what’s aliased –E.g., can’t use t to change j Can’t have a non-const reference alias a const variable –Reverse is OK

10 CSE 332: C++ pointers, arrays, and references Review: Function Parameter Passing int main (int, char *[]) { int h = -1; int i = 0; int j = 1; int k = 2; return func(h, i, j, &k); } int func(int a, const int &b, int &c, int *d) { ++a; c = b; *d = c; ++d; return 0; } By value –Makes a copy i.e., of h into local variable a –++a does not change h By reference –Alias for passed variable –c = b changes j –can’t change b (or i ): const Can pass address by value –And then use address value to change what it points to *d = c; // changes k ++d; // changes local pointer

11 CSE 332: C++ pointers, arrays, and references References to Pointers int main (int, char *[]) { int j = 1; int &r = j; // r aliases j int *p = &r; // p really // points to j int * &t = p; // t aliases p } Can’t have a pointer to a reference –But can point to what the reference aliases Address-of operator on a reference to a variable –Gives address of variable –not of the reference itself Reference to a pointer –An alias for the pointer … not for what it points to –Useful to pass a pointer to code that may change it 0xefffdad0 1 int j int &r int *p 0xefffdad0 0xefffad24 int * &t

12 CSE 332: C++ pointers, arrays, and references Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range” of items) –Allows some useful tricks with addressing –Can make certain algorithms more efficient Array indexes are another form of aliasing –Can interchange with pointer dereferencing –Can do index arithmetic, like pointer arithmetic Arrays can be indexed by enumerated types –Allows labels to be used instead of numbers

13 CSE 332: C++ pointers, arrays, and references Pointers and Arrays int main (int, char **) { int arr[3] = {0, 1, 2}; int * p = &arr[0]; int * q = arr; // p, q both point to arr[0] ++q; // now q points to arr[1] } Array variable itself behaves like a const pointer int * const arr; Set pointers to the start of the array –Using address of 0 th element –Or, just using array name Pointer arithmetic –Adding number n to a pointer Changes pointer’s value By n times the size of the type to which it points Moves pointer n array positions –E.g., value in q is increased by sizeof(int) by ++ q 0xefffdad0 2 int arr[3] int *p 1 0xefffdad4 int *q 0 Notice alternative declaration

14 CSE 332: C++ pointers, arrays, and references Arrays of (and Pointers to) Pointers int main(int argc, char * * argv) { for (int i = 0; i < argc; ++i) { cout << argv[i] << endl; } return 0; } Can have pointers to pointers Can also have an array of pointers (like a const pointer to a pointer type) E.g., argv parameter in main –Array of pointers to character strings –Could also declare as a pointer to the first pointer –Array dimension is not specified –Instead a special argument ( argc ) holds array size By convention, character strings are zero terminated –Special char is ‘\0’ not ‘0’ 0xefffbab0 char * * argv int argc 2 0xefffa0d0 hellotest\0

15 CSE 332: C++ pointers, arrays, and references Example Program: Enumerations and Arrays // arrays.cc // // author: Chris Gill cdgill@cse,wustl.edu // // purpose: definitions for array demonstration program #include "arrays.h" #include // Standard streams and manipulators. // Use symbols from the standard namespace. using namespace std; Let’s look at the header file declarations

16 CSE 332: C++ pointers, arrays, and references Declaring Enumerated Types for Array Indexes // arrays.h // // author: Chris Gill // // purpose: declarations for array demonstration program // same as enum friends {amy = 0, sam = 1, george = 2, // brent = 3, alice = 4, friend_count = 5}; // enum friends {amy, sam, george, brent, alice, friend_count}; // function declarations (prototypes) void print_enumeration (); void print_names (const char * * names, int size); void print_balances (int account_balances[friend_count]); Notice the contiguous values, and the count value Notice no other header files are declared, since not needed

17 CSE 332: C++ pointers, arrays, and references Example Program: Main Function int main (int, char *[]) { const char * names [friend_count] = {"amy", "sam", "george", "brent", "alice"}; // illustrates use of enumerated types print_enumeration (); int account_balances [friend_count]; for (int i = 0; i < friend_count; ++i) { account_balances[i] = 1000; } // pass array and its size print_names (names, friend_count); // just pass the array print_balances (account_balances); return 0; } Can initialize with known set of values Can assign dynamically using a loop and index

18 CSE 332: C++ pointers, arrays, and references Example Program: Enumeration Values /* prints out by iteration: 0 1 2 3 4 5 by individual value: 0 1 2 3 4 5 */ void print_enumeration () { cout << "by iteration: "; for (int i = amy; i <= friend_count; ++i) { cout << i << " "; } cout << endl << "by individual value: “ << amy << " " << sam << " " << george << " " << brent << " " << alice << " " << friend_count << endl; } Can’t use a variable of enumerated type just yet (no operator++ declared) Can use enumerated values directly, though

19 CSE 332: C++ pointers, arrays, and references Example Program: Passing Arrays /* prints out amy sam george brent alice */ void print_names (const char * names [], int size) { for (int i = 0; i < size; ++i) { cout << names [i] << " "; } cout << endl; } /* prints out 1000 1000 1000 1000 1000 */ void print_balances (int account_balances[friend_count]) { for (int i = amy; i < friend_count; ++i) { cout << account_balances[i] << " "; } cout << endl; } Pass dynamically sized array with size variable Can pass fixed-size array by itself

20 CSE 332: C++ pointers, arrays, and references Summary of the Course So Far We’ve focused a lot on “C-level” issues so far –Variable declarations and expressions –Statements and functions –Pointers, arrays, l-values, and r-values We’ve touched on a few additional nuances –Reference variables, exceptions, namespaces These are all a foundation for what’s next –Dynamic memory management operators –Classes, objects, inheritance, virtual functions –Templates, traits, interface polymorphism –The Standard Template Library

21 CSE 332: C++ pointers, arrays, and references For Next Time Topic: C++ Memory Management Assigned Readings –pages 150-156 –pages 166-171 –pages 420-423 –pages 827-829 –pages 837-839


Download ppt "CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object."

Similar presentations


Ads by Google