Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.

Similar presentations


Presentation on theme: "1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers."— Presentation transcript:

1

2 1 Pointers and Strings Chapter 5

3 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers to strings and arrays Pointers can point to functions Declaring & using arrays of strings

4 3 Introduction n Pointer variables contain memory addresses as their values n Contrast normal variables which contain a specific value n x holds a value n xptr holds memory address of some int location int *xptr, x; x 5 xptr

5 4 Pointer Variable Declarations and Initializations n Must declare the type of variable to which pointer variable will point n Must use the leading * to specify this is a pointer variable n Good idea to include ptr in the name of the pointer variable float amt, *fptr;

6 5 Pointer Initialization n When declared, variables should NOT be assumed to have any certain value n As with all variables, pointer variables should be explicitly initialized –Initialized with address of a specific variable –Initialized to 0 or NULL (points to nothing)

7 6 Pointer Operators n Address operator & –unary operator –returns address of operand int *xptr, x; x = 5; xptr = &x; x 5 xptr

8 7 Pointer Operators n Address operator & –unary operator –returns address of operand int *xptr, x; x = 5; xptr = &x; x 5 xptr 1234 1234 6500 Address Values actually stored

9 8 Pointer Operators n The indirection or dereferencing operator –Use the * symbol n *xptr will yield the value stored at the location to which xptr points int x, *xptr; x = 50; xptr = &x; cout << *xptr; // what gets printed? 50

10 9 Pointer Operators n The precedence of –& the address operator –* the dereferencing operator n Higher precedence than multiplication and division n Lower precedence than parentheses

11 10 Calling Functions by Reference n Three ways to pass arguments to a function –call by value –call by reference with reference parameters –call by reference with pointer parameters void doit (int amt); void whatever ( float &value); void fribble (char *ch);

12 11 Calling Functions by Reference n Call by value –value gets passed one way (to the function) only –can use constant, expression, or variable in call n Reference parameter –value passed both ways –must use variable in call –parameter automatically dereferenced locally

13 12 Calling Functions by Reference n Must use address in call –use address operator fribble (&c1); n Must explicitly dereference locally within function –use * operator void fribble (char *ch) { *ch = …. ; }

14 13 Using the const Qualifier with Pointers Recal that const informs the compiler that the value of a "variable" should not be modified n This can also be used on function parameters so that actual parameters are NOT affected by changes in formal parameters void try_a_change (const char *s_ptr)

15 14 const Used on Parameters n When used, do not try to alter contents of where pointer points to void double_int (const int *num_ptr) { *num_ptr = 2 * *num_ptr; } compiler error 

16 15 const Used on Parameters n Consider the advantage of passing large data objects (structures, arrays) using points to constant data –saves memory function does not need to create duplicate data object –saves time program need not copy large number of bytes to the local object

17 16 Bubble Sort Using Call-by- reference n Refer to “Cyber Classroom” CD for author’s description of the program n Run the program

18 17 Bubble Sort Using Call-by- reference -- Note... n array declared as int *array not int array [ ] n Parameter size declared as const to enforce sorting function not altering size –when passing an array to function, send size also -- don’t have it built in n Prototype for swap included inside bubbleSort -- it is the only function that calls swap

19 18 Pointer Expressions & Pointer Arithmetic n Pointer values are valid operands in expressions –arithmetic –assignment –comparison n Not all such operators are valid with pointer variables

20 19 Pointer Expressions & Pointer Arithmetic n Valid operations on pointers ++ - - + += - - = int v[5], *vPtr; vPtr = v; // same as vPtr = &v[0];

21 20 Pointer Expressions & Pointer Arithmetic n Consider: vPtr += 2; // same as vPtr = vPtr + 2; /* But, beware of vPtr -= 4; Why?

22 21 Pointer Expressions & Pointer Arithmetic -- warnings !! n Beware use of pointer arithmetic on pointers which do not reference an array n Consider results of subtracting or comparing two pointers which do not reference the same array n C++ has no range checking -- if you run off the end of an array, you can be in trouble n Pointers can be assigned to other pointers only if they are pointers to the same type –although typecasting can be used (carefully)

23 22 Pointers to void ( void * ) n This is a generic pointer –can represent any pointer type n All pointer types can be assigned a pointer to void without casting n A pointer to void cannot be be assigned a pointer of another type (without casting) n Void pointer cannot be dereferenced (why not??)

24 23 Relationship Between Pointers and Arrays n // Given int list [5], *intPtr; intPtr = list; // name of array is a pointer constant, an address n Then we can use either list[2] or *(intPtr + 2) to reference the second element of the array n The former is clearer but takes longer to compile

25 24 Relationship Between Pointers and Arrays n Note how pointer is used to traverse array: int b[] = { 10, 20, 30, 40 }; int *bPtr = b; // set bPtr to point to array b for ( offset = 0; offset < 4; offset++ ) cout << "*(bPtr + " << offset << ") = " << *( bPtr + offset ) << '\n'; for (bPtr = b; bPtr < b + 4; bPtr++) cout << *bPtr << '\n'; How are these two different?

26 25 Relationship Between Pointers and Arrays n What is wrong with this use of the name of the array? for ( bPtr = b ; b < bPtr + 4; b++ ) cout << *b << '\n'; The name of the array is a pointer constant

27 26 Arrays of Pointers n Common use is for an array of strings (character arrays) char *suit [4] = {"Hearts","Diamonds", "Clubs", "Spades"};

28 27 Arrays of Pointers n Character values stored in memory, one byte longer than length of string Array suit actually holds pointers to these locations –point to first character of each string n Note that memory not wasted for unneeded characters of shorter strings char *suit [4] = {"Hearts", "Diamonds", "Clubs", "Spades"};

29 28 Function Pointers n Pointer to a function contains the address of the function in memory n A function name is a pointer constant to the starting address in memory of the code of the function n Pointers to functions can be … –passed as parameters (both directions) –stored in arrays –assigned to other function pointers

30 29 Function Pointers n Consider the following code: n Function sort receives a pointer to a function –function ascending –function descending void bubble( int [], const int, int (*)( int, int ) ); int ascending( int, int ); int descending( int, int );... void bubble( int work[], const int size, int (*compare)( int, int ) ) depending on pointer passed in call

31 30 Function Pointers n Sending a function name as the actual parameter sends the address of that function to another function if ( order == 1 ) { bubble( a, arraySize, ascending ); cout << "\nData items in ascending order\n"; } else { bubble( a, arraySize, descending ); cout << "\nData items in descending order\n"; }

32 31 Function Pointers n Consider an array of functions void (*f [3] ) ( int ) = { f1, f2, f3 }; n Assumptions –f1, f2, and f3 have been previously declared –each has a single int parameter –they are called with an array number f [ choice ] (x_int);

33 32 Characters and Strings n Character constant –an integer value represented as a character in single quotes 'x' or '\t' n String –series of characters treated as a single unit n String constants (string literals) –enclosed in double quotes "Hi Mom" "2/14/1999"

34 33 Strings An array of characters ending in the null character '\0' n Accessed via pointer to first character in the string n Value of a string –the constant address of its first character Assigned in declaration as array or char pointer char name[ ] = "Snuffy Snail"; char *addr = "123 Frogpond";

35 34 Strings Make sure to allocate enough characters in the array to have room for the '\0' If you create a "string", make sure the '\0' gets tagged on the end n Passing a character as a parameter when a string is expected can cause run time problems n Vice-versa is a syntax error

36 35 String Manipulation Functions Recall that strings must be handled in a special manner char name[30]; name = "Osgood Smart"; n Use functions provided –See page 325 #include –make sure to #include Don't do it!! Why?


Download ppt "1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers."

Similar presentations


Ads by Google