1 The previous lecture Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations Pointer basics 1 Common library functions [Appendix of K+R] <stdio.h> <string.h> <stdlib.h> <ctype.h> getc() putc() printf() scanf() sscanf() sprintf() gets() puts() fgets() fputs() 2 strlen(s) strcpy(s,s) strcat(s,s) strcmp(s,s) <math.h> sin() cos() exp() log() pow() sqrt() ceil() floor() double atof(s) int long void void void int <assert.h> assert() atoi(s) atol(s) rand() system() exit() abs(int) Included in C++ e.g., cstring.h cmath.h int islower(int) int isupper(int) int isdigit(int) int isxdigit(int) int isalpha(int) int tolower(int) int toupper(int) <signal.h>
2 Char arrays: set /get in general Some very import functions you might want to know char message[10]; 0 1 2 3 4 5 6 7 8 9 To get from another string (literal) <string.h> strcpy(message, hello ) 0 1 2 3 4 5 6 7 8 9 H e l l o \0 strcpy(message, OK );? 0 1 2 3 4 5 6 7 8 9 O K \0 l o \0 3 strlen(message)? message[4]? Char arrays: set /get in general other ways of generating a string Some very import functions you might want to know char message[12]; int age = 12; float wage =2.34; Defined in standard library, prototype <stdio.h> sprintf(message, %s %d-%.1f, Sue,age,wage); S u e 1 2-2. 3 \0 sscanf(message, %s %d-%f, name, &age, &wage ); fgets(message, 10, stdin) fputs(message, stdout) tokenizing the string 4 FILE * stream
3 Multidimension array, array of strings char messages[3][7] ={ Hello, Hi, There }; Array of strings 0 1 2 0 1 2 3 4 5 6 H e l l o \0 H i \0 T h e r e \0 Each row (e.g., message[0]) is a char array (string) 5 messages [0] Hello printf( %s, messages[0]); messages [1] Hi printf( %c, messages[2][1]); messages [2] There arrays: set /get in general char message[3][7]; 0 1 0 1 2 3 4 5 6 H e l l o \0 H i \0 strcpy(message[0], hello ) 2 T h e r e \0 sprintf(message, %s there!, hi ); hi ther sprintf(message[1], %s %d %.0f, j, 1, 2.3); sscanf(message[1], %s %d %f, name, &age, &wage ) tokenizing the string fgets(message[2], 7, stdin) fputs(messge[2], stdout) 6
4 Now it is time to start POINTERS!!! 7 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions today Pointer arithmetic Pointers and arrays Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Pointer to functions Pointer to structures Memory allocation Later: file IO
5 Motivations: Calling-by-Value In C, all functions are called by value Value of the arguments are passed to functions, but not the arguments themselves (i.e., not call by reference ) 9 int swap (int x, int y) { int tmp; tmp = x; x = y; y = tmp; } main(){ int i=3, j=4; swap(i,j) } running main() int i = 3 int j = 4 int k int x = i = 3 4 int y = j = 4 3 int tmp 3 running swap() char [] fromstr = Hello! char [20] tostr; strcpy(tostr, fromstr); fgets(tostr, 10, stdin); Given an array as an argument, a function can modify the contents of the array -- Arrays are passed as if call-byreference also scanf ( %d %s, &a, arr); But isn t C call-by-value? -- pass single numerical value 1) How to pass strings to strcpy()? 2) How does strcpy(),scanf(),fgets() modify argument? 10
6 Declare and initialize pointer int *ptr; /* declare a pointer to int */ Create a special variable that stores the address of other variable 4 bytes, why? 91 92 93 94 95 96 97 98 99 100 ptr 0 0 0 0 0 0 0..111 ptr = &x /*assigning address of rate*/ Store address of x in ptr (ptr s value is the address) ptr now points to x 91 92 93 94 95 96 97 98 99 100 0 0 0 0 0 0 0110..0 0 0 0 0 0 0 0..111 x 7 11 96 ptr x int *ptr; /* I m a pointer to an int */ 91 ptr 96 7 x ptr= &x; /*I got the address of rate */ 91 96 96 7 ptr x mnemonic: expression *prt is an int *ptr; /* dereferencing. Indirect assess. Get contents of the pointee*/ ptr &x --- address of x * ptr x --- content (value) of x 12 printf( %d, x ); 7 direct access printf( %d, *ptr); 7 indirect access
7 Some example of Pointers int *p1, *p2; int x = 8, y = 9; p1 = &x; p2 = &y; *p1 = *p2; x = y 100 100 x 100 100 800 800 y 800 800 13 Some example of Pointers int *p1, *p2; int x = 8, y = 9; p1 = &x; p2 = &y; p1 = p2; /*copy the content of p2 (address of y) into p1 */ 100 100 x 800 100 100 100 800 800 y 800 800 800 800 14
8 Some example of Pointers int *p1, *p2, x = 8, y = 9; p1 = &x; p2 = &y; 100 100 100 800 800 800 800 800 x = y 100 100 100 800 100 800 15 800 800 Precedence and Associativity p53 Operator Type Operator Associativity Primary Expression Operators Unary Operators Binary Operators () []. -> left-to-right * & + -! ~ ++ -- (typecast) sizeof * / % arithmetic + - arithmetic >> << bitwise < > <= >= relational ==!= relational & ^ bitwise bitwise bitwise && logical logical right-to-left left-to-right Ternary Operator?: right-to-left Assignment Operators = += -= *= /= %= >>= <<= &= ^= = right-to-left Comma, left-to-right ptr = &x; *x = 5; No () needed
9 ++ * ptr * ptr; * ptr = * ptr + 1 * ++ ptr ptr = ptr +1; *ptr; (* ptr) ++ * ptr; * ptr = * ptr + 1 * ptr ++ * ptr; ptr = ptr +1 17 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions Pointer arithmetic Pointers and arrays Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Pointer to functions Pointer to structures Memory allocation Later: file IO
10 Pointer to pointers int x = 7; int * ptr = &i; 1005 91 ptr_ptr 91 96 96 7 ptr x int ** ptr_ptr = &ptr; /* ptr_ptr = 91 */ ** ptr_ptr = 20; /* set x = 20 */ 91 92 93 94 95 96 97 98 99 100 0 0 0 0 0 0 0110..0 0 0 0 0 0 0 0..111 96 7 91 1000 1001 1002 1003 1004 1005 1006 1004 1005 0 0 0 0 0 0 0110..0 0 0 0 0 0 0 0..111 19 Pointer to pointers another example int x = 12; int *ptr; ptr = &x; 1006 1000 1000 12 ptr x *ptr = 300; 20
11 Pointer to pointers another example int x = 12; int *ptr; ptr = &x; ptr 1000 12 int **ptr-to-ptr /* I am a pointer to pointer */ ptr-to-ptr = &ptr; /* points to ptr */ **ptr-to-ptr = 20; /* multiple indirection*/ valid operations 1012 1006 x, &x *x ptr_to_ptr 1006 1000 x ptr, &ptr, *ptr, **ptr ptr-to-ptr, &ptr_to_ptr *ptr-to-ptr, 21 ** prt-to-ptr, More Examples int x = 1, y = 2; int *ip, *ip2; ip = &x; int **pip /* I am a pointer to pointer */ pip = &ip; /* pip points to ip */ y = **pip; /* y=x y is now 1 */ ip2 = ip; *ip2 += 10; /* x=x+10 x is 11 */ ip = &y; (** pip)--; /* y = y-1 y = 0 */ ip2 = pip;? x? 22 y? 11 0
12 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions Pointer arithmetic Pointers and arrays Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Pointer to functions Pointer to structures Memory allocation Later: file IO Pointers and function arguments In C, all functions are called by value Value of the arguments are passed to functions, but not the arguments themselves (i.e., not call by reference) How to pass a structure such as array? How to modify the argument? swap() How to return structure, and/or more than one values Passing structure and modify by passing pointer Efficient. Input / output Possibly modify passed arguments strcpy (char[] dest, char[] source) 24 strcpy (char * dest, char * source)
13 Mr. Main: Hi, Binding function, I have some manuscripts, stored in lockers (memory), and I want you to bind them into a book. Could I bring the manuscripts to you? main Ms function: Hi, Mr Main, here is how we work: First, we don t take your original manuscript (not pass by reference). We always photocopy things (call by value), and work on copies. Second, we only photocopy one paper a time(a single value) Mr. Main: Then, is there a way to have my original manuscripts bound by you? Calling by Value In C, all functions are called by value Value of the arguments are passed to functions, but not the arguments themselves (i.e., not call by reference) 26 int swap (int x, int y) { int tmp; tmp = x; x = y; y = tmp; } main(){ int a=3, b=4; swap(a,b); } running main() int a =3 int b = 4 int x = a= 3 int y = b=4 int tmp 4 3 3 call swap() running swap()
14 Mr. Main: Hi, Mrs binding function, I have some manuscripts, stored in lockers (memory), and I need you to bind them into a book. Could I bring the manuscripts to you? main Ms function: Hi, Mr Main, here is how we work: First, we don t take your original manuscript (not pass by reference). We always photocopy things (call by value), and work on copies. Second, we only photocopy one paper a time(a single value) Mr. Main: Then, is there a way to have my original papers bound by you? Ms function: Write down the locker number (address) on a paper, bring that paper to us (pass pointer/address) we photocopy the paper (still pass by value), Then, based on the locker number on the copy, we go to your locker, fetch your original manuscripts there and bind them! Mr. Main: Cool! The Correct Version I am expecting int pointers void swap(int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; } px = &a; py = &b px = &a; py = &b; void main( ) { int a=2, b=40; swap(&a, &b); } 28 printf( %d %d, a, b);
15 The Correct Version I am expecting int pointers void swap(int *px, int *py) { } int temp; temp = *px; *px = *py; *py = temp; void main( ) { int a=2, b=40; int *pa=&a; int *pb=&b; swap(pa,pb); printf( %d %d, a, b); } 29 px = pa = &a; py = pb = &b The other way to pass address px = pa = &a; py = pb = &b; Another example void increment(int *px2, int *py2) { (*px2) ++;? (*py2) += 30; } void swapincre(int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; increment(?,?); } increment(px, py) void main( ) { int a=2, b=40; /* Input a and b */ swapincre(&a, &b); printf( %d %d, a, b); }30
16 Now understand scanf() -- more or less int x=1; int y = 2; swap(&x,&y); int x; scanf ( %d, &x); printf( %d,x); int x; int *px = &x; scanf( %d, px); printf( %d,*px); But why array name is used directly scanf ( %s, arrname) scanf ( %d %s, &x, arrname) 31 scanf( %d, &px);? // store input value into px, not x Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions Pointer arithmetic Pointers and arrays Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Pointer to functions Pointer to structures Memory allocation Later: file IO
17 Pointers and variable type base type is important! int x = 1, y = 2; int *ip; ip = &x; /* ip points to x */ y = *ip; /* y is now 1 */ 91 92 93 94 95 96 97 98 99 100 oo.1 0..0 0..11 0 0 0 0 0 0 0..111 c sh i Each pointer stores the address of the first byte of its pointee How many bytes to transfer? -- Base type is important! 33 int i; char c; short sh; int* pi; char *pc; short *psh; Pointers and variable type base type is important! 91 92 93 94 95 96 97 98 99 100 oo.1 0..0 0..11 0 0 0 0 0 0 0..111 c sh i int* pi = &i; char *pc=&c; short *psh=&sh; Each point store the address of the first byte of its pointee How many bytes to transfer? Base type is important! Allowing proper read/write. y = *pi; *pi = 100; r/w 4 bytes from 96 [96,97,98,99] c = *pc; *pc= d ; r/w 1 byte from 91 s=*psh; *psh=2; r/w 2 bytes from 93 [93, 94] 34
18 Pointer arithmetic pi pi+1 91 92 93 94 95 96 97 98 99 100 oo.1 0..0 0..11 0 0 0 0 0 0 0..111 c sh i Limited math on a pointer Four arithmetic operators that can be applied + - ++ -- Result is a pointer (address) int* pi=&i; char * pc=&c; short * psh=&sh; 35 pi + 1? address 96+ 4 =100 psh + 2? address 93+ 2 + 2 = 97. pi ++? pc++? psh++? pi = 96 + 4 pc = 91 + 1 psh = 93 + 2 Pointer arithmetic Incrementing / decrementing a pointer by n moves it ahead n units p ± n unit Size of a unit is based upon the size of the type If p points to an integer of 4 bytes, p + n advances by 4*n bytes: p + 2 = 96 + 4*2 = 104 p p+1 p+2 95 96 97 98 99 100 104 108 *p *(p+1) *(p+2) 36 How would we need to move pointer?
19 arithmetic2017.c Arithmic.c int * pint; short * pshort; char * pchar; double * pdouble; 37 +1n +2n +4n +8n Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions Pointer arithmetic Pointers and arrays (5.3) Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Pointer to functions Pointer to structures Memory allocation Later: file IO
20 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic + - ++ -- Pointers and arrays (5.3) How arrays are stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) Array as function argument decay Pass sub_array Later: file IO Pointers and Arrays (5.3) Array members are next to each other in memory arr[0] occupies in the lowest address e.g. int arr[3]; 91 92 93 94 95 96 97 98 99 100 101 102 103 104 arr[0] arr[1] arr[2] short 40
21 Array members are next to each other in memory arr[0] occupies in the lowest address 91 92 93 94 95 96 97 98 99 100 101 102 103 104 arr[0] arr[1] arr[2] arrayelementsize2017.c 41 Array members are next to each other in memory arr[0] occupies in the lowest address 91 92 93 94 95 96 97 98 99 100 101 102 103 104 arr[0] arr[1] arr[2] 42 + 1 + 4 + 4 + 8
22 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic +- ++ -- Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) Array as function argument decay Pass sub_array Later: file IO Pointers and Arrays (5.3) Array members are next to each other in memory arr [0] occupies in the lowest address e.g. if x is an integer array int x[3]; 44 91 92 93 94 95 96 97 98 99 100 101 102 103 104 arr[0] arr[1] arr[2] int arr[3]; int *ptr; ptr = &x[0]; ptr + 1?; /* &arr[1] */ ptr = ptr + 2; /* ptr = &arr[2] */ *(ptr +2 ) =. /* *&arr[2] access arr[2] */ ptr + i == & arr[i] *(ptr + i) == arr[i]
23 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic +- ++ -- Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) Array as function argument decay Pass sub_array Later: file IO Pointers and Arrays (5.3) There is special relationship between pointers and arrays when you use array, you are using pointers! int i, arr[20], char c; scanf( %d %c %s, &i, &c, arr); /* &arr is wrong */ Identifier (name) of an array is equivalent to the address of its 1 st element. arr == &arr[0] arr + 1 == address of next element == &arr[1] *(arr + 20) == *(&arr[20]) == arr[20] int arr[20]; int * p; ptr = arr; /* == (ptr = &arr[0]) */ ptr + 8 == & arr[8] *(ptr + 8) == arr[8] 46 Pass (copy) to a function (arr) -- the address of arr[0]
24 Pointers and Arrays (5.3) There is special relationship between pointers and arrays Identifier (name) of an array is equivalent to the address of its 1 st element. arr == &arr[0] int arr[20]; int * p; ptr = arr; /* ptr = &arr[0] */ arr[4] *(ptr + 4) *(arr + 4) equivalent 47 ptr[4]; Pass (copy) to a function (arr) -- the address of arr[0] arrayaddressppp.c /* Demonstrates use of pointer arithmetic in array*/ main() { int arr[10] = {0,10,20,30,40,50,60,70,80,90}, x; int *ptr = arr; /* = &arr[0] */ printf( %p %p, arr, prt); /* Print the addresses of each array element. */ for (x = 0; x < 10; x++) printf("%p %p %p", &arr[x], arr+x, ptr+x); /* Print the content of each array element. */ for (x = 0; x < 10; x++) printf( %d: %d %d %d", arr[x], *(arr+x), *(ptr+x), ptr[x]); } 48 return 0;
25 arr == &arr[0] + 4 49 Another way ++ /* Demonstrates use of pointer arithmetic in array*/ main() { int arr[10] = {0,10,20,30,40,50,60,70,80,90}, x; int *ptr = arr; /* = &arr[0] */ /* Print the addresses of each array element. */ for (x = 0; x < 10; x++) printf("%p %p %p", &arr[x], arr+x, ptr++); /* Print the content of each array element. */ for (x = 0; x < 10; x++) printf("%d %d %d", arr[x], *(arr+x), *(ptr++)); 50 } return 0; arr++???
26 Array name is not pointer! int arr[20]; int * p = arr; p and arr are equivalent and they have the same properties: &arr[0] Difference is that arr is a string constant we could assign another value to the pointer p arr will always point to the first of the 20 integer numbers of type int. p = arr; /*valid*/ arr = p; /*invalid*/ p++; /*valid*/ arr++; /*invalid*/ 51 char arr[10] = hello ; int i; char * p; p = arr; strlen(arr); /*valid*/ sizeof (arr)? strlen(p); /*valid*/ sizeof (p)? arr = NULL; /*invalid*/ arr = &i; /*invalid*/ arr = arr +1; /*invalid*/ arr ++; /*invalid*/ *(arr + 1)=5 /*valid*/ p = NULL; p++; p = &i; 52 /*valid*/ /*valid*/ /*valid. now point to others*/
27 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic +- ++ -- Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) Array as function argument decay Pass sub_array Later: file IO Pointer arithmetic (revisit) +n -n ++ -- If p1, p2 points to different elements of the same array Differencing: p1 p2 how far apart the elements are Comparison : ==!= > < >= <= p1 < p2 is true (1) if p1 points to earlier elements than p2 p1 p2 54
28 Pointer arithmetic on arrays (revisit) Adding an Integer to a Pointer Adding an integer j to a pointer p yields a pointer to the element j places after the one that p points to. More precisely, if p points to the array element a[i], then p + j points to a[i+j]. Assume that the following declarations are in effect: int a[10], *p, *q, i; 55 55 Pointer arithmetic on arrays (revisit) Adding an Integer to a Pointer 7 Example of pointer addition: p = &a[2]; q = p + 3; p += 6; Assume int array. Assume p= &a[2] = 96 Then q = 96+ 3 4 =108 = &a[5] 56
29 Pointer arithmetic on arrays (revisit) Subtracting an Integer from a Pointer If p points to a[i], then p - j points to a[i-j]. Example: p = &a[8]; 7 q = p - 3; p -= 6; Assume int array. assume p= &a[8] = 120 Then q = 120-3 4 =108 = &a[5] 57 Pointer arithmetic on arrays (revisit) Subtracting One Pointer from Another When one pointer is subtracted from another, the result is the distance (measured in array elements) between the pointers. If p points to a[i] and q points to a[j], 7 then p - q is equal to i - j. p = &a[5]; // 108 q = &a[1]; // 92 i = p - q; /* i is 4 (108-92)/4 = 4 */ i = q - p; /* i is -4 */ 58
30 Pointer arithmetic on arrays (revisit) Comparing Pointers Pointers can be compared using the relational operators (<, <=, >, >=) and the equality operators (== and!=). Using relational operators is meaningful only for pointers to elements of the same array. The outcome of the comparison depends on the relative positions of the two elements in the array. 59 p = &a[5]; q = &a[1]; p <= q is 0 false p >= q is 1. true Summary of pointer arithmetic Legal: assignment of pointers of the same type p2 = p1 adding or subtracting a pointer with an integer p++, p+2, p-2 subtracting or comparing two pointers to members of the same array p2- p1, if (p1 < p2) assigning or comparing to zero (NULL) p = NULL p==null Illegal: add two pointers, multiply or divide two pointers, integers shift or mask pointer variables p1+p2; p1*p2; p1*3 add float or double to pointers p1 + 1.23 assign a pointer of one type to a pointer of another type (except for void *) without a cast 60
31 Pointers and Arrays: an Example int a[10]={3,4,5,6}; int *pa; pa = a; /* pa=&a[0] */ 0 1 2 3 4 5 6 7 8 9 3 4 5 6 0 0 0 0 0 0 int x,y,z; x = *pa; /*same as x = a[0]*/ y = *(pa + 1); //a[1] z = *(pa + 2); //a[2] pa++; x = *(pa+2)? *(pa + 3) = 200; 61 3 4 5 6 0 0 0 0 0 0 3 4 5 6 0 0 0 0 0 0 x:6 y:4 z:5 a: 3 4 5 6 200 0 0.. 0 Pointers K&R Ch 5 Basics: Declaration and assignment Pointer to Pointer Pointer and functions (pass pointer by value) Pointer arithmetic +- ++ -- Pointers and arrays (5.3) Stored consecutively Pointer to array elements p + i = &a[i] *(p+i) = a[i] Array name contains address of 1 st element a = &a[0] Pointer arithmetic on array (extension) p1-p2 p1<>!= p2 Array as function argument decay Pass sub_array Arrays of pointers Command line argument Pointer to arrays and two dimensional arrays Pointer to functions Pointer to structures Memory allocation file IO today