Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 9 Pointers.

Similar presentations


Presentation on theme: "Module 9 Pointers."— Presentation transcript:

1 Module 9 Pointers

2 @Copyright UMBC Training Centers 2012
Pointer Basics In this lesson we will learn the basic syntax for declaring and using pointers Upon completion of this lesson, you will be able to Declare pointer variables Use pointer syntax to assign and dereference pointers Evaluate expressions that use pointers @Copyright UMBC Training Centers 2012

3 @Copyright UMBC Training Centers 2012
What is a Pointer A pointer variable (or simply “pointer”) is a variable that contains the memory address (location) of another variable Powerful, but dangerous if not used with discipline The variable to which the pointer points is known as the “pointee” @Copyright UMBC Training Centers 2012

4 @Copyright UMBC Training Centers 2012
Why Pointers? Pointers… lead to compact and efficient code. facilitate sharing data between different parts of an application. make it possible to get dynamically allocated memory when your application is executing. make it easy to represent relationships among data items. @Copyright UMBC Training Centers 2012

5 @Copyright UMBC Training Centers 2012
Pointer Caution They are a powerful low-level device. Undisciplined use can be confusing and thus the source of subtle, hard-to-find bugs. Program crashes Memory leaks Unpredictable results @Copyright UMBC Training Centers 2012

6 @Copyright UMBC Training Centers 2012
Declaring Pointers The general declaration of a pointer is type *nameOfPointer; For example int *pInt; @Copyright UMBC Training Centers 2012

7 @Copyright UMBC Training Centers 2012
Pointer Operators The & operator gives the address of a variable pInt = &age; assigns the address of age to the pointer pInt, and we say that pInt “points to” age; The * operator uses the pointer to access the pointee x = *pInt; assigns the value in the variable to which pInt points (the pointee) to x, and we say that we are “dereferencing” the pointer. @Copyright UMBC Training Centers 2012

8 @Copyright UMBC Training Centers 2012
Pointers in Memory int myAge, yourAge, *pAge; myAge = 42; pAge = &myAge; yourAge = *pAge + 3; @Copyright UMBC Training Centers 2012

9 @Copyright UMBC Training Centers 2012
More Pointer Code int *ip = NULL, x = 1, y = 2; int z[3] = {0}; ip = &x; y = *ip; *ip = 0; *ip = *ip + 10; ip = &y; printf( “%d”, *ip); scanf(“%d”, ip); ip = &z[2]; *ip = x + y; @Copyright UMBC Training Centers 2012

10 @Copyright UMBC Training Centers 2012
Let’s take a look C::B – pointer1 Show 1st half of the code, have students predict the output Trace the code on board, then run the code Do the same with 2nd half of code @Copyright UMBC Training Centers 2012

11 @Copyright UMBC Training Centers 2012
Broken swap( ) void swap (int a, int b) { int temp = a; a = b; b = temp; } int main( ) { int x = 42, y = 77; swap(x, y); printf(“x = %d, y = %d\n”, x, y); @Copyright UMBC Training Centers 2012

12 @Copyright UMBC Training Centers 2012
Exercises pointers2 – students trace code and predict output Pg 277 #10 – rewriting char array code to use char* @Copyright UMBC Training Centers 2012

13 Initialized Strings Revisited
As an array of chars char name1[ ] = “Jimmy”; Using a CHAR pointer char *name2 = “Jimmy”; @Copyright UMBC Training Centers 2012

14 @Copyright UMBC Training Centers 2012
String Parameters void printString1( char[ ] string) { printf(“%s\n”, string); } void printString2( char* string ) … printManyStrings( char* strings[], int count) for(int s = 0; s < count; s++) printf(“%s\n”, strings[s]); @Copyright UMBC Training Centers 2012

15 Initialized Array of Strings
char* names[3] = { “Bobby”, “Jim”, “Mary” }; printf (“My name is %s\n”, names[1]); @Copyright UMBC Training Centers 2012

16 @Copyright UMBC Training Centers 2012
Let’s take a look C::B – copyString (From the text; we would write this using while loop) Explain the array of char version General array copying algorithm Must append NUL char to end of “to” to make it a C-String Reveal and explain the pointer version @Copyright UMBC Training Centers 2012

17 @Copyright UMBC Training Centers 2012
End of Day 1 Exercises Pg 276 #1 (11.1, ) #10 – Rewrite compareStrings from Ch10 using pointers #12 – printf with strings; predict first Ex5-DateStrings – create and use arrays of strings @Copyright UMBC Training Centers 2012

18 @Copyright UMBC Training Centers 2012
Pointer Parameters Pointer parameters allow us to simulate passing arguments “by reference” Argument is a pointer to a variable Parameter is a copy of the pointer Allows a function to alter the argument from within the function @Copyright UMBC Training Centers 2012

19 @Copyright UMBC Training Centers 2012
swap( ) /* swap the values of pointees */ void swap (int *ip1, int *ip2) { int temp = *ip1; *ip1 = *ip2; *ip2 = temp; } int main() int x = 42, y = 77; int *ptrToX, *ptrToY; ptrToX = &x; ptrToY = &y; swap( ptrToX, ptrToY ); return 0; @Copyright UMBC Training Centers 2012

20 @Copyright UMBC Training Centers 2012
Let’s take a look C::B PointersAndFunction1 @Copyright UMBC Training Centers 2012

21 @Copyright UMBC Training Centers 2012
“Output” Parameters void convertTime (int time, int *pHours, int *pMins) { *pHours = time / 60; *pMins = time % 60; } int main( ) int time, hours, minutes; printf("Enter a time duration in minutes: "); scanf ("%d", &time); convertTime (time, &hours, &minutes); printf("HH:MM format: %02d:%02d\n", hours, minutes); return 0; @Copyright UMBC Training Centers 2012

22 @Copyright UMBC Training Centers 2012
An Exercise void myFunction (int a, int *b) { a = 7 ; // line 1 *b = a ; // line 2 b = &a ; // line 3 *b = 4 ; // line 4 printf("%d, %d\n", a, *b) ; // line 5 } int main() int m = 3, n = 5; // line 6 myFunction(m, &n) ; // line 7 printf("%d, %d\n", m, n) ; // line 8 return 0; @Copyright UMBC Training Centers 2012

23 @Copyright UMBC Training Centers 2012
Pointer to Structure typedef struct point { int x, y; } POINT; POINT center = {5, 10}; // structure initialization POINT corner = {3, 9}; POINT *pPoint; pPoint = &center; printf(“Center at (%d, %d)\n”, pPoint->x, pPoint->y); pPoint = &corner; printf(“Corner at (%d, %d)\n”, pPoint->x, pPoint->y); // less common but equivalent printf(“Center at (%d, %d)\n”, (*pPoint).x, (*pPoint.y)); @Copyright UMBC Training Centers 2012

24 @Copyright UMBC Training Centers 2012
Let’s take a look C::B – nap (name, address, person) Lot of functions with pointer to struct as parameters Start discussion with NAME, then ADDRESS, then finally PERSON @Copyright UMBC Training Centers 2012

25 Pointer to struct parameter
void inputPoint( struct point *pPoint) { printf(“Please input point coordinates: ”); scan(“%d %d”, &(pPoint->x), &(pPoint->y)); } void printPoint( struct point *pPoint) printf(“(%d, %d)”, pPoint->x, pPoint->y); int main( ) struct point center; inputPoint( &center ); printPoint( &center ); return 0; @Copyright UMBC Training Centers 2012

26 Structures Containing Pointers
struct intPtrs { int *p1, *p2; }; struct intPtrs bob; int int1 = 100, int2; bob.p1 = &int1; bob.p2 = &int2; *bob.p2 = -97; @Copyright UMBC Training Centers 2012

27 @Copyright UMBC Training Centers 2012
NULL NULL is a predefined special value for pointers Points to “nothing” Some programmers like to initialize all pointers to NULL when they are defined double *pRatio = NULL; Program termination if we dereference a pointer that is NULL @Copyright UMBC Training Centers 2012

28 @Copyright UMBC Training Centers 2012
Exercises Text, #1 pg 275 Ex1-Coins2 – nr coins from N cents (pointer parameters) Ex2-Division Ex3-Money – pointer to struct as function parameter Ex4 – People – struct parameters/return values @Copyright UMBC Training Centers 2012

29 @Copyright UMBC Training Centers 2012
End of Day 1?? @Copyright UMBC Training Centers 2012

30 @Copyright UMBC Training Centers 2012
Pointers and Arrays Arrays are commonly used to store data In C, there is an intimate relationship between pointers and arrays @Copyright UMBC Training Centers 2012

31 @Copyright UMBC Training Centers 2012
Basics int a[4] = {11, 13, 15, 17}; int *ip, x; ip = &a[0]; x = *ip; x = *(ip + 1); x = *(ip + 2); @Copyright UMBC Training Centers 2012

32 @Copyright UMBC Training Centers 2012
The Big Ideas If ip points to a[0], then ip + i points to a[i] and *(ip + i) is synonymous with a[i] More generally, ip + i points i elements beyond where ip is pointing The statement ip = ip + i; moves ip to point i elements beyond where it currently points @Copyright UMBC Training Centers 2012

33 @Copyright UMBC Training Centers 2012
More Big Ideas Since the name of an array is synonymous with the address of (pointer to) its first element… The name of an array can be thought of as a pointer to the first element of the array and vice-versa ip = a; is equivalent to ip = &a[0]; *(ip + i), *(a + i) and ip[i] are all equivalent to a[i] @Copyright UMBC Training Centers 2012

34 @Copyright UMBC Training Centers 2012
Let’s take a look CB – PointersAndArrays1 typical code and you should use [ ] with arrays – clearer going to see array code that uses pointers instead it’s important that we examine the different ways to write this code First create a new pointer variable and change the code in the for-loop to use pointer arithmetic ADD int *pWeight = &weights[ 0 ] ; change weights[i] to *(pWeight+i) As the for-loop changes the value of I, pWeight+I iterates through the elements of the array, just like before To show that “weights” acts like a pointer, change pWeight to “weights” @Copyright UMBC Training Centers 2012

35 Arrays and Functions Revisited
Array name is a pointer to its first element Array parameter could be replaced with a pointer parameter Compiler treats array parameters as pointers Reflected in error messages Use an array parameter if the function uses an index to access the members of an array @Copyright UMBC Training Centers 2012

36 @Copyright UMBC Training Centers 2012
Let’s take a look CB -- PointersAndArrays2 change array parameter to a[300] to illustrate that parameter is just the address of where the array is located in memory… a “pointer” change array parameter to pointer parameter change code to *(a + i) Error messages related to the array parameter will use pointer terminology Change int a[] to float a[] and look at the log @Copyright UMBC Training Centers 2012

37 @Copyright UMBC Training Centers 2012
What’s the difference? Between an array and a pointer variable A pointer is a variable that can point to different variables during execution Array name is NOT a variable and can only “point to” its first element Now we know why scanf does not require & for %s arguments @Copyright UMBC Training Centers 2012

38 @Copyright UMBC Training Centers 2012
Let’s take a look C::B - ConstPointers CB: PtrExpressions – hand out table to be completed by students C::B CompareStrings Modify to use pointer+offset @Copyright UMBC Training Centers 2012

39 Initialized Strings Revisited
As an array of chars char name1[ ] = “Jimmy”; Using a pointer char *name2 = “Jimmy”; @Copyright UMBC Training Centers 2012

40 @Copyright UMBC Training Centers 2012
Let’s take a look C::B – copyString Explain the array of char version General array copying algorithm Must append NUL char to end of “to” to make it a C-String Reveal and explain the pointer version @Copyright UMBC Training Centers 2012

41 @Copyright UMBC Training Centers 2012
Array of Strings char *names[3] = { “Bobby”, “Jim”}; names[2] = “Mary”; printf (“My name is %s\n”, names[1]); @Copyright UMBC Training Centers 2012

42 @Copyright UMBC Training Centers 2012
String Parameters printString1( char string[] ) { printf(“%s\n”, string); } printString2( char *string ) printManyStrings( char *strings[ ], int count) for(int s = 0; s < count; s++) printf(“%s\n”, strings[s]); @Copyright UMBC Training Centers 2012

43 @Copyright UMBC Training Centers 2012
More String Functions char *strchr(char * string, char c) returns a pointer to the first occurrence of c in string or NULL if not found char *strpbrk(char *s1, char *s2) returns a pointer to the first occurrence of any character in s2 found in s1 or NULL if not found char *strrchr(char * string, char c) returns a pointer to the last occurrence of c in string or NULL if not found char* strstr(char *s1, char *s2) returns a pointer to the first occurrence of s2 in s1 or NULL if not found @Copyright UMBC Training Centers 2012

44 @Copyright UMBC Training Centers 2012
Let’s take a look C::B – String Functions Add code after strchr() to find the next ‘w’ add code after strchr( ) call to print index where ‘w’ is found by showing pointer subtraction @Copyright UMBC Training Centers 2012

45 @Copyright UMBC Training Centers 2012
Exercises PtrExpressions.docx experimenting with ++*p, etc Ex4-DateStrings @Copyright UMBC Training Centers 2012

46 More Pointer Operations
To access array elements and traverse through the array use *arrayPtr++ Dereferences arrayPtr,then increments it void copyString( char *to, char *from ) { while (*from) *to++ = *from++; *to = ‘\0’; } @Copyright UMBC Training Centers 2012

47 @Copyright UMBC Training Centers 2012
Let’s take a look Ex3-PointerExpression @Copyright UMBC Training Centers 2012

48 @Copyright UMBC Training Centers 2012
Exercises Text #8 – function to sort 3 integers with pointer params (not array) #12 Ex2-ExchangeSort (same as Ex7) Ex5-DateStrings Ex6 – Gymnastic Scores – array as function parameters Ex7-Gettysburg – string functions that return pointer @Copyright UMBC Training Centers 2012

49 @Copyright UMBC Training Centers 2012
If you have any comments about this video, please use the contact information in your registration materials to let us know @Copyright UMBC Training Centers 2012


Download ppt "Module 9 Pointers."

Similar presentations


Ads by Google