Lecture 8 POINTERS 1 Outline n n n

  • Slides: 25
Download presentation
Lecture 8: POINTERS 1

Lecture 8: POINTERS 1

Outline n n n n n Introduction Pointer Variable Definitions and Initialization Pointer Operators

Outline n n n n n Introduction Pointer Variable Definitions and Initialization Pointer Operators Calling Functions by Reference Using the const Qualifier with Pointers Pointer Expressions and Pointer Arithmetic The Relationship between Pointers and Arrays of Pointers to Functions 2

Introduction n Pointer is the address(i. e. a specific memory location) of an object

Introduction n Pointer is the address(i. e. a specific memory location) of an object It can refer to different objects at different times Pointers are used in C programs for a variety of purposes: n n To return more than one value from a function(using pass by reference) To create and process strings To manipulate the contents of arrays and structures To construct data structures whose size can grow or shrink dynamically 3

Pointer Variable Definitions and Initialization n Pointer variables n n Contain memory addresses as

Pointer Variable Definitions and Initialization n Pointer variables n n Contain memory addresses as their values Normal variables contain a specific value (direct reference) num 7 n n Pointers contain address of a variable that has a specific value (indirect reference) Indirection – referencing a pointer value num. Ptr num 7 4

Pointer Variable Definitions and Initialization n Pointer definitions n n Use ‘ptr’ to avoid

Pointer Variable Definitions and Initialization n Pointer definitions n n Use ‘ptr’ to avoid confusion when declaration. * used with pointer variables int *num. Ptr; n n Defines a pointer to an int (pointer of type int *) Multiple pointers require using a * before each variable definition int *num. Ptr 1, *num. Ptr 2; n n Can define pointers to any data type Initialize pointers to 0, NULL, or an address n 0 or NULL – points to nothing (NULL preferred) n int *num. Ptr = NULL; OR int *num. Ptr = 0; 5

Pointer Operators n Symbol & is called address operator n Returns address of operand

Pointer Operators n Symbol & is called address operator n Returns address of operand int num = 7; int *num. Ptr; num. Ptr = # /* num. Ptr gets address of num */ num. Ptr “points to” num. Ptr num 7 num. Ptr 500000 600000 num 600000 7 Address of num is value of num. Ptr 6

Pointer Operators • Symbol * is called indirection/dereferencing operator – Returns a synonym/alias of

Pointer Operators • Symbol * is called indirection/dereferencing operator – Returns a synonym/alias of what its operand points to • *num. Ptr returns num (because num. Ptr points to num) – * can also be used for assignment • Returns alias to an object *num. Ptr = 10; /* changes num to 10 */ show pictures!! – Dereferenced pointer (operand of *) must be an lvalue (no constants) • * and & are inverses – They cancel each other out num. Ptr num 7

Sample program a #include <stdio. h> int main() { int a; int *a. Ptr;

Sample program a #include <stdio. h> int main() { int a; int *a. Ptr; a = 7; a. Ptr = &a; 0012 FF 7 C 7 printf(“The address of a is %p” “n The value of a. Ptr is %p”, &a, a. Ptr); printf(“nn The value of a is %d” “n The value of *a. Ptr is %d”, a, *a. Ptr); printf(“nn Showing that * and & are complements of each other” “n &*a. Ptr = %p n *&a. Ptr = %p n”, &*a. Ptr, *&a. Ptr); return 0; } 8

9

9

10

10

Calling Functions by Reference n Call by reference with pointer arguments n n Pass

Calling Functions by Reference n Call by reference with pointer arguments n n 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 n Used as alias/nickname for variable inside of function void fun 1( int *number ) { // assume *number = 10; *number = 2 * ( *number ); } n *number used as nickname for the variable passed 11

Enter character : f Do you want to continue? y Enter character : I

Enter character : f Do you want to continue? y Enter character : I Do you want to continue? y Example Enter character : k Do you want to continue? n Number of vowel : 1 Number of consonant : 2 #include <stdio. h> #include <string. h> char read(); void find_count_vc(char, int*); void print(int, int); int main() { char ch, choice; int count_v=0, count_c=0; do { ch = read(); find_count_vc(ch, &count_v, &count_c); printf("Do you want to continue? "); scanf("%c", &choice); getchar(); }while((choice == 'y') ||(choice =='Y')); print(count_v, count_c); return 0; } char read() { char ch 1; printf("Enter character : "); scanf("%c", &ch 1); getchar(); return(ch 1); } void find_count_vc(char ch 1, int *vowel, int *consonant) { switch(ch 1) { case 'A': Functions that “return” case 'a': case 'E': more than one value i. e. case 'e': arguments are passed by case 'I': ref case 'i': case 'O': case 'o': case 'U': case 'u': *vowel = *vowel +1; break; default: *consonant = *consonant + 1; } } void print(int vowel, int consonant) { printf("Number of vowel : %dn", vowel); printf("Number of consonant : %dn", consonant); } 12

Pointer Expressions and Pointer Arithmetic n Arithmetic operations that can be performed on pointers:

Pointer Expressions and Pointer Arithmetic n Arithmetic operations that can be performed on pointers: n Increment and Decrement (++ , --) n Addition and Subtraction (+ or +=, - or -=) n n Comparison (==, !=, <, >, <=, >=) Assignment (=) 13

Pointer Expressions and Pointer Arithmetic n 5 element int array on machine with 4

Pointer Expressions and Pointer Arithmetic n 5 element int array on machine with 4 byte ints n n v. Ptr points to first element v[ 0 ] n at location 3000 (v. Ptr = 3000) v. Ptr += 2; sets v. Ptr to 3008 n v. Ptr points to v[ 2 ] (incremented by 2), but the machine has 4 byte ints, so it points to address 3008 location 3000 v[0] pointer variable v. Ptr 3004 v[1] 3008 v[2] 3012 v[3] 3016 v[4] 14

Pointer Expressions and Pointer Arithmetic n Subtracting pointers n Returns number of elements from

Pointer Expressions and Pointer Arithmetic n Subtracting pointers n Returns number of elements from one to the other. Assume: v. Ptr 2 = &v[ 2 ]; v. Ptr = &v[ 0 ]; n n x = v. Ptr 2 - v. Ptr // x = ? two Pointer comparison (==, !=, <, >, <=, >=) n n See which pointer points to the higher numbered array element Also, see if a pointer points to 0 15

Pointer Expressions and Pointer Arithmetic n Pointers of the same type can be assigned

Pointer Expressions and Pointer Arithmetic n Pointers of the same type can be assigned to each other n n If not the same type, a cast operator must be used Exception: pointer to void (type void *) n n Generic pointer, represents any type No casting needed to convert a pointer to void pointers cannot be dereferenced Example: (char*) 19456 – convert integer 19456 to a char pointer 16

Pointer operation: example #include <stdio. h> int main() {int *v. Ptr; int *v. Ptr

Pointer operation: example #include <stdio. h> int main() {int *v. Ptr; int *v. Ptr 2; int v[5] = {10, 20, 30, 40, 50}; int temp; v. Ptr 1245064 1245020 v. Ptr= &v; printf("Address of v. Ptr : %d Contents of v. Ptr : %dn", &v. Ptr, v. Ptr); printf("Address of v[0] : %dn", &v); v. Ptr +=2; printf("Address of v. Ptr + 2: %dn", v. Ptr); v. Ptr +=2; printf("Address of v. Ptr + 4: %dn", v. Ptr); v. Ptr 2=&v[2]; v. Ptr=&v[0]; temp=v. Ptr 2 -v. Ptr; printf("Contents of temp : %dn", temp); return 0; } 17

The Relationship Between Pointers and Arrays n Arrays and pointers closely related n n

The Relationship Between Pointers and Arrays n Arrays and pointers closely related n n n Array name like a constant pointer Pointers can do array subscripting operations Define an array b[ 5 ] and a pointer b. Ptr n To set them equal to one another use: b. Ptr = b; n The array name (b) is actually the address of first element of the array b[ 5 ] b. Ptr = &b[ 0 ] n Explicitly assigns b. Ptr to address of first element of b 18

Relationship Btw Pointers and Arrays – Accessing array elements with pointers – Element b[

Relationship Btw Pointers and Arrays – Accessing array elements with pointers – Element b[ n ] can be accessed by *( b. Ptr + n ) • Called pointer/offset notation – Addresses • &b[ 3 ] same as b. Ptr + 3 – Array name can be treated as pointer • b[ 3 ] same as *( b + 3 ) – Pointers can be subscripted (pointer/subscript notation) 19 • b. Ptr[ 3 ] same as b[ 3 ]

Example b. Ptr #include <stdio. h> int main() 1245064 1245016 { int *b. Ptr

Example b. Ptr #include <stdio. h> int main() 1245064 1245016 { int *b. Ptr ; int i; int b[10]={10, 20, 30, 40, 50}; b. Ptr = b; printf("Address of b. Ptr : %d Contents of b. Ptr : %dn", &b. Ptr, b. Ptr); printf("Address of b : %d Contents of b[0]: %d %d %dn", &b, b[0], *b. Ptr, *b); printf("b. Ptr points to b[0] = %dn", *b. Ptr); printf("n. I am accessing element b[3]!!n. Let see how many ways I can do itn"); printf("b[3] = %dn", b[3]); printf("*(b. Ptr + 3) = %dn", *(b. Ptr + 3)); printf("*(b + 3) = %dn", *(b + 3)); printf("b. Ptr[3] = %dnn", b. Ptr[3]); for(i=0; i<10; i++) printf("b[%d] = %dn", i, *(b. Ptr+i)); return 0; } 20

Exercise #include <stdio. h> int main () { int numbers[5]; int * p; p

Exercise #include <stdio. h> int main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) printf( "%d “, numbers[n]); return 0; } 21

Arrays of Pointers n n Arrays can contain pointers For example: an array of

Arrays of Pointers n n Arrays can contain pointers For example: an array of strings char *suit[ 4 ] = { “Hearts", “Diamonds", "Clubs", "Spades" }; n n Strings are pointers to the first character char * – each element of suit is a pointer to a char n The strings are not actually stored in the array suit, only pointers to the strings are stored 22

Arrays of Pointers suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’�’ suit[1] ’D’ ’i’

Arrays of Pointers 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’ n ’s’ ’’ suit array has a fixed size, but strings can be of any size 23

Example #include <stdio. h> #define N 5 int main() { char *student. Name[N]; int

Example #include <stdio. h> #define N 5 int main() { char *student. Name[N]; int i; for(i=0; i<5; i++) { printf("Enter student[%d] name : ", i); scanf("%s", student. Name + i); printf("You just entered : n%sn", student. Name + i); } return 0; } Enter student[0] name You just entered : ali Enter student[1] name You just entered : abu Enter student[2] name You just entered : cheah Enter student[3] name You just entered : dali Enter student[4] name You just entered : gheeta : ali : abu : cheah : dali : gheeta 24

#include <stdio. h> int main () { int b[ ] = {10, 20, 30,

#include <stdio. h> int main () { int b[ ] = {10, 20, 30, 40}; int *b. Ptr = b; int i, offset; Exercise printf(“Array b printed with: n. Array subscript notationn”); for(i=0; i<4; i++) { printf(“b[%d] = %dn”, i, b[i]); } printf(“n. Pointer/offset notation wheren The pointer is the array namen”); for(offset=0; offset<4; offset++) { printf(“*(b + %d) = %dn”, offset, *(b + offset)); } printf(“n. Pointer subscript notationn”); for(i=0; i<4; i++) { printf(“b. Ptr[%d] = %dn”, i, b. Ptr [i]); } printf(“n. Pointer/offset notationn”); for(offset=0; offset<4; offset++) { printf(“*(b. Ptr + %d) = %dn”, offset, *(b. Ptr + offset)); } return 0; } 25