Department of Computer and Information Science School of

  • Slides: 30
Download presentation
Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Dale

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 Dale Roberts

What is Pointer CS Dept. Location A: Highway Intersection Phone rings and says “Deliver

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

What is Pointer Example: Find out who is with Woodstock Pig Pen Sally Lucy

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

Pointer declarations: datatype snoopy, *charlie, **linus; snoopy = ; /* snoopy’s content is Woodstock

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 snoopy. Ptr (Snoopy’s pointer) and rewrite linus using variable of snoopy. Ptr (pointer of Snoopy’s pointer); Note that this is a naming convention. The only requirement is that the variable be a valid identifier: begin with a letter followed by letters, digits or _. Dale Roberts

Pointer Variable Declarations and Initialization Pointers Definition: A pointer is a variable that contains

Pointer Variable Declarations and Initialization Pointers Definition: 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-byreference and create/manipulate dynamic data structures Close relationship with arrays and strings Dale Roberts

Pointer variables Contain memory addresses as their values Normal variables contain a specific value

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

Pointer Variable Declarations Pointer Declarations type *variable_name * used with pointer variables Example: int

Pointer Variable Declarations Pointer Declarations type *variable_name * used with pointer variables Example: int *my. Ptr; 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 *my. Ptr 1, *my. Ptr 2; float *pq; char *pc; Dale Roberts

Pointer Variable Initialization Initialize pointers to 0, NULL, or an address 0 or NULL

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

Pointer Operators &: Address Operator Returns address of operand y. Ptr int y =

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

Pointer Operators * : Indirection / De-referencing Operator Returns a synonym/alias of what its

Pointer Operators * : Indirection / De-referencing Operator Returns a synonym/alias of what its operand points to *yptr returns y (because yptr points to y) * 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 Dale Roberts

1 /* Fig. 7. 4: fig 07_04. c 2 Using the & and *

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

Pointer Operators Example: int i = 5; int *pi; pi = &i; /* place

Pointer Operators Example: int i = 5; int *pi; pi = &i; /* place the address of i into pi */ Assume variable address value at the address i pi 874 5 902 874 pi 902 874 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; Dale Roberts i 874 5

Example: int i, *pi, **ppi; i = 5; pi = &i; ppi = π

Example: int i, *pi, **ppi; i = 5; pi = &i; ppi = π 108 ppi 104 Variable Address Value at address i 100 5 pi 104 100 ppi 108 104 pi 100 i 5 Usage Meaning Value pi address of int 100 *pi int value 5 &pi address of pointer 104 ppi address of pointer 104 *ppi address of int 100 **ppi int value 5 Dale Roberts

Calling Functions by Reference Call by reference with pointer arguments Pass address of argument

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 Use as alias/nickname for variable inside of function void double_num ( int *number ) { *number = 2 * ( *number ); } *number used as nickname for the variable passed. It is a formal parameter, that corresponds to an actual parameter. Dale Roberts

Example of Calling Functions by Value 1 /* 2 Cube a variable using call-by-value

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

Example of Calling Functions by Value int main() { int number = 5; number

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

Example of Calling Functions by Reference 1 /* Fig. 7. 7: fig 07_07. c

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

Example of Calling Functions by Reference Before the call by reference to cube. By.

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

Using the const Qualifier with Pointers const qualifier Variable cannot be changed Use 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 COMPUTER MEMORY Point to a constant memory location Must be initialized when declared 1) int *const my. Ptr 1 = &x 1; Type int *const Constant pointer to an int x can be changed, but not *Ptr 2) Ptr const int *const Ptr = &x 3; const pointer to a const int Dale Roberts x 3 case 3 my. Ptr 1 x 2 case 1 const int *my. Ptr 2 = &x 2; Regular pointer to a const int 3) CONSTANT MEMORY AREA x 1 case with using const my. Ptr VARIABLE MEMORY AREA my. Ptr 2 x

1 /* Fig. 7. 13: fig 07_13. c 2 Attempting to modify a constant

1 /* Fig. 7. 13: fig 07_13. c 2 Attempting to modify a constant pointer to 3 non-constant data */ 4 5 #include <stdio. h> 6 7 int main() 8 { 9 Declare variables 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; Changing *ptr is allowed – x is not a constant. 17 18 19 } return 0; Changing ptr is an error – ptr is a constant pointer. Declare const pointer to an int Change *ptr (which is x) Attempt to change ptr FIG 07_13. c: Error E 2024 FIG 07_13. c 16: Cannot modify a const object in function main *** 1 errors in Compile *** Dale Roberts Output

Pointer Expressions and Pointer Arithmetic pv+n pv + n*sizeof(variable type that pointer point to)

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: ++v. Ptr , v. Ptr++, --v. Ptr, v. Ptr-- Add an integer to a pointer( + or += , - or -=) Pointers may be subtracted from each other Operations meaningless unless performed on an array Dale Roberts

Example: Five element int array on machine with 4 byte ints v. Ptr points

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

Pointer Expressions and Pointer Arithmetic Example: (double pointer) Assume long (long integer) is 4

Pointer Expressions and Pointer Arithmetic Example: (double pointer) Assume long (long integer) is 4 bytes, and pointer variable is 2 Questions: bytes. long a[10]={5, 10, 15, …}; long *pa, **ppa; a int i=5; 640 5 pa = &a; 644 10 ppa = &pa; 800 700 ppa 648 15 652 656 660 700 640 pa Variable Address Value a 640 5 644 10 648 15 … … pa 700 640 ppa 800 700 Expression Value Note pa+1 644 640+1*4 pa+3 652 640+3*4 pa+i 660 640+i*4 ppa+1 702 700+1*2 ppa+i 710 700+i*2 *pa+1 6 5+1 *(pa+1) 10 a[1]=pa[1]=*(a+1) pa[2] 15 648 *ppa 640 value of pa *ppa+1 644 pa+1 *(ppa+1) invalid *(702) **ppa+1 6 a[0]+1 = 5+1 *(*ppa+1) Dale Roberts 10 *(pa+1)=*(640+1*4)

Pointer Expressions and Pointer Arithmetic Subtracting pointers Returns number of elements from one to

Pointer Expressions and Pointer Arithmetic Subtracting pointers Returns number of elements from one to the other. If v. Ptr 2 is a pointer pointing to v[ 2 ]; v. Ptr is a pointer pointing to v[ 0 ]; v. Ptr 2 - v. Ptr 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 pointers cannot be dereferenced Dale Roberts

The Relationship Between Pointers and Arrays and pointers are closely related Array name like

The Relationship Between Pointers and 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 b. Ptr = b; // To set them equal to one another // The array name (b) is actually the address of first element of the array b. Ptr = &b[ 0 ]; // Explicitly assigns b. Ptr to address of first element of b To access element b[ 3 ]: x=*( b. Ptr + 3 ) // Where n is the offset. Called pointer/offset notation x=bptr[ 3 ] // Called pointer/subscript notation // b. Ptr[ 3 ] same as b[ 3 ] x=*( b + 3 ) // Performing pointer arithmetic on the array itself Dale Roberts

Pointers and Arrays Strong relation between pointers and arrays Pointers and arrays can be

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[i] *(pa+i) pa[i] *(a+i) &a[i] pa+i a[i]+=5 *(pa+i)+=5 pa[i]+=5 Example: f(int s[]) f(int *s) { … } } Dale Roberts

Arrays of Pointers Arrays can contain pointers For example: an array of strings char

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 The strings are not actually stored in the array suit, only pointers to the strings are stored suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’’ suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’’ suit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’’ suit array has a fixed size, but strings can be of any size Dale Roberts

Pointers to Functions Pointer to function Contains address of function Similar to how array

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 Dale Roberts

Example: Bubble Sort #define SIZE 10 void bubble(int [], const int, int (*)(int, int));

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 swap( int *element 1 Ptr, int *element 2 Ptr ) { int temp; temp = *element 1 Ptr; *element 1 Ptr = *element 2 Ptr; *element 2 Ptr = 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*/ } 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]); } Dale Roberts

Function bubble takes a function pointer bubble calls this helper function this determines ascending

Function bubble takes a function pointer 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 If the parentheses were left out: bool *compare( int, int ) Declares a function that receives two integers and returns a pointer to a bool Dale Roberts