Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Dale Roberts, Lecturer Computer Science, IUPUI.

Similar presentations


Presentation on theme: "Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Dale Roberts, Lecturer Computer Science, IUPUI."— Presentation transcript:

1 Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu

2 Dale Roberts What is Pointer Bring your money to IUPUI ET-202 to exchange hostage “Find Instruction Under The crabapple tree next to old law school ” “Find next message on the top of traffic light on Michigan St. and West St. Phone rings and says “Deliver ransom to I-65 and West St. intersection Hostage Location A: Highway Intersection Location B: Traffic Light Location C: Crabapple Tree Location D: IUPUI ET-202 CS Dept. CSABCD Address of next location A pointer is an address.

3 Dale Roberts What is Pointer Pig Pen points to Lucy; Lucy points to Sally; Sally points to Linus; Linus points to Charlie; Charlie points to Snoopy; Snoopy has Woodstock Example: Find out who is with Woodstock among peanut gang ? Snoopy CharlieLinus … Pig Pen “ Lucy knows ” Lucy “Sally knows” Sally “ Linus knows ” Linus “ Charlie knows ” Charlie “ Snoopy is ” Woodstock Woodstock is with Snoopy Snoopy An instance uses a pointer to link to a next instance making a chain.

4 Dale Roberts Pointer declarations: datatype snoopy, *charlie, **linus; snoopy = ; /* snoopy’s content is Woodstock */ charlie = &snoopy; /* charlie’s content is the info (pointer) to locate snoopy, which is snoopy’s address */ linus = &charlie; /* linus’s content is the info (pointer) to locate charlie, which is charlie’s address*/ In general, we can rewrite charlie using variable of snoopyPtr (Snoopy’s pointer) and rewrite linus using variable of snoopyPtrPtr (pointer to Snoopy’s pointer); Note that this is only a naming convention. The only requirement is that the variable be a valid identifier: begin with a letter followed by letters, digits or _.

5 Dale Roberts Pointer Variable Declarations and Initialization PointersDefinition: A pointer is a variable that contains address of another variable. Most powerful feature of C, but difficult to master Pointers enable programs to simulate call-by- reference and create/manipulate dynamic data structures Close relationship with arrays and strings

6 Dale Roberts Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain address of a variable that has a specific value (indirect reference) Indirection – referencing a pointer value count 7 7 countPtr

7 Dale Roberts Pointer Declarations type *variable_name * used with pointer variables * used with pointer variables Example: int *myPtr; Declares a pointer to an int (pointer of type int * ) Multiple pointers require using a * before each variable declaration Can declare pointers to any data type Example: int *myPtr1, *myPtr2; float *pq; char *pc; Pointer Variable Declarations

8 Dale Roberts Pointer Variable Initialization Initialize pointers to 0, NULL, or an address 0 or NULL – points to nothing ( NULL preferred) Example: int *ptr, x; x=10; ptr = &x; 5000 ptr FFFF x 5000 ptr x 10 FFFF 5000 ptr FFFF x 10

9 Dale Roberts Pointer Operators & : Address Operator Returns address of operand int y = 5; int *yPtr; yPtr = &y; /* yPtr “points to” y */ /* yPtr gets address of y */ yptr 500000600000 y 5 yPtr y 5 address of y is the value of yPtr

10 Dale Roberts Pointer Operators * : Indirection / De-referencing Operator Returns a synonym/alias of what its operand points to *yptr returns y (because yptr points to y ) *yptr returns y (because yptr points to y ) * can be used for assignment that returns alias to an object * can be used for assignment that returns alias to an object *yptr = 7; // changes y to 7 Dereferenced pointer (operand of * ) must be a variable (no constants) * and & are inverses They cancel each other out

11 Dale Roberts 1/* Fig. 7.4: fig07_04.c 2 Using the & and * operators */ 3#include 4 5int main() 6{6{ 7 int a; /* a is an integer */ 8 int *aPtr; /* aPtr is a pointer to an integer */ 9 10 a = 7; 11 aPtr = &a; /* aPtr set to address of a */ 12 13 printf( "The address of a is %p" 14 "\nThe value of aPtr is %p", &a, aPtr ); 15 16 printf( "\n\nThe value of a is %d" 17 "\nThe value of *aPtr is %d", a, *aPtr ); 18 19 printf( "\n\nShowing that * and & are inverses of " 20 "each other.\n&*aPtr = %p" 21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr ); 22 23 return 0; 24} The address of a is 0012FF88 The value of aPtr is 0012FF88 The value of a is 7 The value of *aPtr is 7 Proving that * and & are complements of each other. &*aPtr = 0012FF88 *&aPtr = 0012FF88 The address of a is the value of aPtr. The * operator returns an alias to what its operand points to. aPtr points to a, so *aPtr returns a. Notice how * and & are inverses Note the use of %p format. 1. Declare variables 2 Initialize variables 3. Print Program Output ( The address of the variable that aPtr points to ) ( The content in the address location of aPtr ) 7 a 0012FF88 aPtr 00FFFFFF

12 Dale Roberts Pointer Operators Example: int i = 5; int *pi; pi = &i; /* place the address of i into pi */ Assume Symbol Table i.e. &i = 874, i = 5; &pi = 902, pi = 874; *pi = ? *pi = 5; // same as i = 5; *pi = *pi * 2; // same as i = i * 2; *pi *= 2; // same as i *= 2; 874902 5 pii 874 variableaddressvalue at the address i 8745 pi 902874

13 Dale Roberts Example: int i,*pi,**ppi; i = 5; pi = &i; ppi = π 100104108 5 ppipii 100104 VariableAddressValue at address i1005 pi104100 ppi108104 UsageMeaningValue pi address of int 100 *piint value 5 &pi address of pointer 104 ppi address of pointer 104 *ppi address of int 100 **ppiint value 5

14 Dale Roberts Calling Functions by Reference Call by reference with pointer arguments Pass address of argument using & operator Allows you to change actual location in memory Arrays are not passed with & because the array name is already a pointer * Operator * Operator Used as alias/nickname for variable inside of function void double_num ( int *number ) { *number = 2 * ( *number ); } *number used as nickname for the variable passed

15 Dale Roberts 1 /* 2 Cube a variable using call-by-value 3 */ 4 5#include 6 7int cubeByValue( int ); /* prototype */ 8 9int main() 10{ 11 int number = 5; 12 13 printf( "The original value of number is %d", number ); 14 number = cubeByValue( number ); 15 printf( "\nThe new value of number is %d\n", number ); 16 17 return 0; 18} 19 20int cubeByValue( int n ) 21{ 22 return n * n * n; /* cube number in main */ 23} The original value of number is 5 The new value of number is 125 Function prototype Initialize variables Call function Define function Program Output Example of Calling Functions by Value

16 Dale Roberts int main() { int number = 5; number = cubeByValue( number ); } int main() { int number = 5; number = cubeByValue( number ); } int main() { int number = 5; number = cubeByValue( number ); } int main() { int number = 5; number = cubeByValue( number ); } int main() { int number = 5; number = cubeByValue( number ); } int cubeByValue( int n ) { return n * n * n; } int cubeByValue( int n ) { return n * n * n; } int cubeByValue( int n ) { return n * n * n; } int cubeByValue( int n ) { return n * n * n; } int cubeByValue( int n ) { return n * n * n; } number 5 5 5 5 125 n undefined n 5 n 5 n n 125 Example of Calling Functions by Value

17 Dale Roberts 1/* Fig. 7.7: fig07_07.c 2 Cube a variable using call-by-reference 3 with a pointer argument */ 4 5#include 6 7void cubeByReference( int * ); /* prototype */ 8 9int main() 10{ 11 int number = 5; 12 13 printf( "The original value of number is %d", number ); 14 cubeByReference( &number ); 15 printf( "\nThe new value of number is %d\n", number ); 16 17 return 0; 18} 19 20void cubeByReference( int *nPtr ) 21{ 22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */ 23} The original value of number is 5 The new value of number is 125 Notice how the address of number is given - cubeByReference expects a pointer (an address of a variable). Inside cubeByReference, *nPtr is used (* nPtr is number ). Notice that the function prototype takes a pointer to an integer ( int * ). Function prototype Initialize variables Call function Define function Program Output Example of Calling Functions by Reference

18 Dale Roberts Example of Calling Functions by Reference int main() { int number = 5; cubeByReference( &number ); } int main() { int number = 5; cubeByReference( &number ); } int main() { int number = 5; cubeByReference( &number ); } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; } number 5 nPtr undefined n nPtr Before the call by reference to cubeByReference: After call by reference to cubeByReference and before *nPtr is cubed: After *nPtr is cubed : number 5 nPtr address of number 125 address of number

19 Dale Roberts COMPUTER MEMORY CONSTANT MEMORY AREA VARIABLE MEMORY AREA x1 myPtr1 x2 myPtr2 x3 Ptr x myPtr case 1 case 2 case 3 case with using const Using the const Qualifier with Pointers const qualifier Variable cannot be changed Use const if function does not need to change a variable Attempting to change a const variable produces an error const pointers Point to a constant memory location Must be initialized when declared 1) int *const myPtr1 = &x1; Type int *const Constant pointer to an int x can be changed, but not *Ptr 2) const int *myPtr2 = &x2; Regular pointer to a const int 3) const int *const Ptr = &x3; const pointer to a const int

20 Dale Roberts 1/* Fig. 7.13: fig07_13.c 2 Attempting to modify a constant pointer to 3 non-constant data */ 4 5#include 6 7int main() 8{8{ 9 int x, y; 10 11 int * const ptr = &x; /* ptr is a constant pointer to an 12 integer. An integer can be modified 13 through ptr, but ptr always points 14 to the same memory location. */ 15 *ptr = 7; 16 ptr = &y; 17 18 return 0; 19} FIG07_13.c: Error E2024 FIG07_13.c 16: Cannot modify a const object in function main *** 1 errors in Compile *** Changing *ptr is allowed – x is not a constant. Changing ptr is an error – ptr is a constant pointer. Declare variables Declare const pointer to an int Change *ptr (which is x ) Attempt to change ptr Output

21 Dale Roberts Pointer Expressions and Pointer Arithmetic pv+n  pv + n*sizeof ( variable type that pointer point to ) Arithmetic operations can be performed on pointers Increment/decrement pointer ( ++ or -- ) Example: ++vPtr, vPtr++, --vPtr, vPtr-- Add an integer to a pointer( + or +=, - or -= ) Pointers may be subtracted from each other Operations meaningless unless performed on an array

22 Dale Roberts Example: Five element int array on machine with 4 byte int s vPtr points to first element v[ 0 ] whose address location is 3000 ( vPtr = 3000 ) vPtr points to first element v[ 0 ] whose address location is 3000 ( vPtr = 3000 ) vPtr += 2 ; vPtr += 2 ; // sets vPtr to 3008 vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 byte integers, so it points to address 3008 vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 byte integers, so it points to address 3008 pointer variable vPtr v[0]v[1]v[2]v[4]v[3] 30003004300830123016 location

23 Dale Roberts Example: (double pointer) Assume long (long integer) is 4 bytes, and pointer variable is 2 bytes. long a[10]={5, 10, 15, …}; long *pa, **ppa; int i=5; pa = &a; ppa = &pa; Pointer Expressions and Pointer Arithmetic VariableAddressValue a6405 64410 64815 …… pa700640 ppa800700 ExpressionValueNote pa+1644640+1*4 pa+3652640+3*4 pa+i660640+i*4 ppa+1702700+1*2 ppa+i710700+i*2 *pa+165+1 *(pa+1)10 a[1]=pa[1]=*(a+1) pa[2]15648 *ppa640value of pa *ppa+1644pa+1 *(ppa+1)invalid*(702) **ppa+16a[0]+1 = 5+1 *(*ppa+1)10 *(pa+1)=*(640+1*4) ppapa 640700 800 a 5 10 15 640 644 648 652 656 660 Questions:

24 Dale Roberts Pointer Expressions and Pointer Arithmetic Subtracting pointers Returns number of elements from one to the other. If vPtr2 is a pointer pointing to v[ 2 ]; vPtr is a pointer pointing to v[ 0 ]; vPtr2 - vPtr would produce 2 vPtr2 - vPtr would produce 2 Pointer comparison ( ) See which pointer points to the higher numbered array element Also, see if a pointer points to 0 Pointers of the same type can be assigned to each other If not the same type, a cast operator must be used Exception: pointer to void (type void * ) Generic pointer, represents any type No casting needed to convert a pointer to void pointer void pointers cannot be dereferenced

25 Dale Roberts The Relationship Between Pointers and Arrays Arrays and pointers are closely related Array name like a constant pointer Pointers can do array subscripting operations Example: Declare an array b[ 5 ] and a pointer bPtr bPtr = b; // To set them equal to one another // The array name ( b ) is actually the address of first element of the array bPtr = &b[ 0 ]; // Explicitly assigns bPtr to address of first element of b To access element b[ 3 ]: x=*( bPtr + 3 ) // Where n is the offset. Called pointer/offset notation x=bptr[ 3 ] // Called pointer/subscript notation // bPtr[ 3 ] same as b[ 3 ] x=*( b + 3 ) // Performing pointer arithmetic on the array itself

26 Dale Roberts Pointers and Arrays Strong relation between pointers and arrays Pointers and arrays can be used interchangeably. The array name is equivalent to the address of the first element in the array Example: int a[10]; int *pa; pa = &a[0]; /* is equivalent to pa = a */ So, a[1]  *(pa+1)  pa[1]  *(a+1) &a[1]  pa+1  a+1 a[i]  *(pa+i)  pa[i]  *(a+i) &a[i]  pa+i  a+i a[i]+=5  *(pa+i)+=5  pa[i]+=5 Example: f(int s[]) { … } f(int *s) { … } 

27 Dale Roberts Arrays of Pointers Arrays can contain pointers For example: an array of strings char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"}; Strings are pointers to the first character char * – each element of suit is a pointer to a char char * – each element of suit is a pointer to a char The strings are not actually stored in the array suit, only pointers to the strings are stored suit array has a fixed size, but strings can be of any size suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0]’H’’e’’a’’r’’t’’s’ ’\0’ ’D’’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’

28 Dale Roberts Pointers to Functions Pointer to function Contains address of function Similar to how array name is address of first element Function name is starting address of code that defines function Function pointers can be Passed to functions Stored in arrays Assigned to other function pointers

29 Dale Roberts void swap( int *element1Ptr, int *element2Ptr ) { int temp; temp = *element1Ptr; *element1Ptr = *element2Ptr; *element2Ptr = temp; } int ascending( int a, int b ) { return b < a; /*swap if b is less than a*/ } int descending( int a, int b ) { return b > a; /*swap if b is greater than a*/ } Example: Bubble Sort #define SIZE 10 void bubble(int [],const int, int (*)(int,int)); int ascending( int, int ); int descending( int, int ); int main() { int a[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; bubble( a, SIZE, ascending ); bubble( a, SIZE, descending ); } void bubble( int work[], const int size, int (*compare)(int,int)) { int pass, count; void swap( int *, int * ); for (pass=1; pass<size; pass++) for (count=0; count<size-1; count++) if ((*compare)(work[count],work[count+1])) swap(&work[count],&work[count + 1]); }

30 Dale Roberts Function bubble takes a function pointer bubble calls this helper function bubble calls this helper function this determines ascending or descending sorting The argument in bubblesort for the function pointer: bool ( *compare )( int, int ) tells bubblesort to expect a pointer to a function that takes two ints and returns a bool tells bubblesort to expect a pointer to a function that takes two ints and returns a bool If the parentheses were left out: bool *compare( int, int ) Declares a function that receives two integers and returns a pointer to a bool


Download ppt "Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Dale Roberts, Lecturer Computer Science, IUPUI."

Similar presentations


Ads by Google