1、Chapter 9:Pointers,Instructor : Dandan Song,Can address store in memory?,Why should address store in memory?,Outline,9.1 Basics of Pointers 9.2 Array and Function9.3 Pointer and Function 9.4 Pointer and Array9.5 Points to a Pointer,What is a pointer (指针) ? -A pointer is a variable that contains the
2、address of a variable. How memory is organized in PC? -A typical machine has an array of consecutively numbered or addressed memory cells that may be manipulated individually or in contiguous groups. A pointer is a group of cells (often two or four) that can hold an address.,9.1 Basics of Pointers,E
3、g: int a,*p;p= /*pointer variable p stores address of a*/,直接访问 (Direct access)通过变量名访问该变量。,间接访问 (Indirect access) 通过指针变量中存放的地址访问该变量,int a=10; printf(“%dn”,a);,int a=10,*p=,定义变量: int k;编译系统根据int为k分配内存单元。,输入变量的值:scanf(“%d”,&k代表了变量k在内存中的地址。,变量pk是一个指针变量,存放k的地址,称”指向k”,指针就是地址! 指针变量就是存放地址的变量!,Basic concepts
4、,main( ) int a , b , c ;a=5 ,b=10 ;c=a+b; printf(“%d,%d,%d”, a,b,c); ,main( ) int a , b , c, *pc ;a=5 ,b=10 ; pc=,/*Direct access c*/,/* Indirect access c by pointer pc */,Compare:,指针可以指向所有类型的数据,指针指向变量-变量的指针(存变量的地址),指针指向数组-数组的指针(存数组的起始地址),指针指向函数-函数型指针(存放函数的入口地址),指针指向指针-指针型指针(存放某指针的地址),由指针组成的数组-指针数组,
5、指针是定位其他数据类型的特殊类型的数据(存放其他数据的地址),Data_type *pointer_name =initial_value ,Basic type,Data_type is the variable type pointer points to; * is pointer indication,indicates a pointer variable (also an indirect access operator),int a , *pa;,pa= /pa can only points to an integer,*pa=10; /indirect access a, a
6、=10;,int a,*pa=,Definition and Initialization,*address,get variable content in the address,int a=5,*p; p= /*equals a=10+a */ *p*(&a) a,definition,Operation,Using of a pointer,main( ) int a,b,c,d,e, *pa= ,输出: 30,30,30,31,There are three kinds of basic operations for pointer: Addition operation and su
7、btraction operation between a pointer and a positive integer. Relational operation between two pointers. Subtraction operation between two pointers.Besides, pointer recursion will be discussed as a special operation.,There are two unary operators for pointer :& : gives the address of an object.* : a
8、ccesses the object the pointer points to.,9.1 Basics of Pointers (con.),Addition operation and subtraction operation between a pointer and a positive integer.,Assume: pointer p points to the element of the array, and n is a positive integer.,p + n means that p points to the n-th element after the cu
9、rrent element. p n means that p points to the n-th element before the current element. p+ / +p means that p adds to one; points to the next element. p- - / - -p means that subtracts one from p; points to the previous element.,p-3,p-1,p-2,p,p+1,p+2,p+3,lower,higher,Example9_1.1: Connect two strings.,
10、char * strcat (char *str1, char *str2) char *p=str1;while ( *p!=0 ) p+;while ( *p+ = *str2+ );return (str1); main( ) char a50, b30;printf(“Enter string 1:“); gets(a);printf(“Enter string 2:“); gets(b);printf(“a+b=%sn“, strcat(a, b) ); ,Condition: Only when two pointers point to the same array, there
11、 exist several relational operations (, =, =, !=, =) between them. For example: two pointers p and q. (pq): when the element p points to is before the one q points to, the expression is true (1); else false (0). (p=q): when point to the same element, the expression is true (1); else false (0). Besid
12、es, (p=NULL) or (p!=NULL) describe whether pointer p points to the empty.,Relational operation between two pointers.,revstr ( char * s ) /* reverse string*/ char *p=s, c;while ( *p )p+; /* find 0 of the string */p-; /* p points to the last element of array */while ( sp ) /* head s end p */ c = *s; /
13、* swap elements two pointers point to */*s+ = *p; /* assign first, then +1, head s moves backward */*p- = c; /* assign first, then -1, end p moves forward */ ,Example9_1.2: Reverse string.,Subtraction operation between two pointers.,Condition: only when two pointers point to the same array.Assume po
14、inter p and pointer q point to the same array, (p - q) describes the storage size (number of memory cells) between two elements which two pointers point to.,strlen (char *s) char *p = s;while ( *p ) p+;return ( p s ); ,Example9_1.3: Calculate the string length.,a,b,c,d,e,f,g,0,Length = 7,s,p=s+7,Poi
15、nter Recursion,Analysis: When string is empty (only exists 0), such as “”, the length is zero (0). When string is not empty, in another word, it can be divided into two parts: first element + others, the length is equivalent to add one to the length of others. formula: length of string = 1 + length
16、of others,Example9_1.4: Calculate the string length by using pointer recursion.,strlen (char * s) if (*s = 0) return (0) ;else return (1+ strlen (s+1) ) ; ,Pointer Recursion (con.),Analysis: 1. 将给定的字符串分为两个部分: 第一部分:第一个字符和最后一个字符(0前的字符); 第二部分:从第二个字符到倒数第二个(即中间的字符); 其中第二部分与原问题性质一样,只是缩小了规模。 2. 基本算法 交换第一部分
17、的两个字符; 将第二部分构成一个字符串,递归:完成第二部分串反向.Algorithm 首先定义两个字符指针分别指向字符串的首字符和除0以外的最后一个字符; 将所指的两个字符进行交换; 使中间部分构成“新的”字符串,并对其进行串反向操作.,Pointer Recursion (con.),Example9_1.5: Reverse the string by using pointer recursion.,revstr ( char * s ) char *p = s, c;while ( *p )p+;p-; /* */if ( s p ) c = *s;*s = *p; /* */*p =
18、 0; /* */revstr(s+1);*p = c; /* */ ,Pointer Recursion (con.),a,a,f,0,If s p,recursion,The relationship between array and function:Transfer some elements (arguments) of the array among functions; Passed by value; Passed by address.,Transfer the whole array among functions. Pass one-dimension array; P
19、ass multi-dimension array.,9.2 Array and Function,Transfer some elements,Each element of the array is equivalent to an ordinary variable functionally, therefore elements could be considered as function arguments. Transfer methods include: Passed by value: elements are arguments; common variables are
20、 parameters. Passed by address: elements address are arguments; pointer variables are parameters.,Passed by value,Example9_2.1: Find three integers a, b and c, which should satisfy the below formula: abc = a! + b! + c!,main ( ) int i, j, k, m, a3, flag; for ( j=101; j6 ) flag = 0; else m += fac( ai
21、); if ( flag ,Example9_2.2: swap corresponding (subscripts) elements between array_a and array_b.,#include swap ( int *pa, int *pb ) int temp; temp = *pa; *pa = *pb; *pb = temp; main( ) int a5 = 1, 2, 3, 4, 5 ; int b5 = 10,20,30,40,50 , i; for ( i=0; i5; i+ ) swap ( ,Passed by address,During pass a
22、one-dimension array among functions: Array name is argument; Array name is also parameter, however, it should follow a pair of blank square brackets ( ).,Explanation: Actually passed by first address of the array. In another word, calling function and caller function share with the same array. Becau
23、se the size of the parameter array is decided by the argument array, there could be nothing inside the square brackets.,Transfer the whole array,Example9_2.3: calculate the average value of all elements of an one-dimension array.,main ( ) float average( );static float a10 = 1, 1.1, 1.2, 1.3, 1.4, 1.
24、5, 1.6, 1.7, 1.8, 1.9;printf (“The average is %fn“, average( a, 10) ); float average ( float a , int n ) int i; float sum=0;for ( i=0; in; i+ ) sum += ai;return (sum/n); ,For example : declare the multi-dimension array uses as parameter. To two-dimension:int a34; or int a 4; To three-dimension:int a
25、334; or int a 34;Cannot int a 4; int a3 4;Cannot int a33 ; int a ;,Transfer the whole array (con.),During pass a multi-dimension array among functions: Array name is argument; Array name is also parameter, however, the size of the array is optional (only could omit the size of the first-dimension).,
26、Example9_2.4: Calculate the sequence number of the day in a year according to the given date.,main( ) static int day_tab213 = 0, 31, 28, 31, 30, 31,30,31,31,30,31,30,31, 0, 31, 29, 31, 30, 31,30,31,31,30,31,30,31 ;int y, m, d; scanf (“%d%d%d“, ,Example9_4.6,Example9_4.3,1. Pointer as arguments Actua
27、lly there exists the relationship between pointers and function arguments. Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function. Pointer arguments enable a function to access and change objects in the function that
28、 called it.,More discuss in Chapter 8 (Section 2: arguments passed by “address”). Typical example: swap two values,9.3 Pointer and Function,2. function return pointer,return char: char min(char a10) char i,m;m=a0;for(i=1;iai) m=ai;return m;,return char * char *min(char a10) char i,*m;m= ,type *,3. p
29、oints to a function,int (*p)( ); p是指向int函数的指针变量 p=max; p是指向int型函数max的指针变量,function pointer:entrance address of a function(函数的入口地址-用函数名表示),(1) Definition,int max(int x, int y) return xy?x:y; main( ) int c,a=15,b=12,(*p)( );p=max; /*p points to max()*/c=(*p)(a,b);/*call function*/printf(“max=%dn”,c);
30、,call a function using function pointer,c=max(a,b);,2. Application,9.4 Pointer and Array,The relationship between pointer and arrayPointer Arrays (指针数组) Array Pointers (数组指针) Command-line ArgumentsA Storage Allocator,In C, there is a strong relationship between pointers and arrays, strong enough tha
31、t pointers and arrays should be discussed simulaneously.,The relationship between pointer and array,Any operation that can be achieved by array subscripting can also be done with pointers. The pointer version will be faster but harder to understand.,Assume : int a100;,Array_name: a Address of the el
32、ement: &ai First_address (or initial address): is the address of the first element (&a0), also is the name of the array (a). C Language Principle: a = &a0 -The name of an array is a synonym (同义词) for the address of the initial element.,Example9_4.1: analyze below program.,#include main ( ) int a = 1
33、, 2, 3, 4, 5 ;int x, y, *p; /* p is a pointer */p= ,main( ) int a = 1, 2, 3, 4, 5,;int *p; p=a; printf (“nt %d“, *p );printf (“nt %d“, *(+p) ); printf (“nt %d“, *+p );printf (“nt %d“, *(p-) );p += 3;printf(“nt%dt%d“, *p, *(a+4) ); ,Example9_4.2: analyze below program.,p,p,p,p,p,p,points to,address,a
34、rray,#include main( ) static int day_tab213 = 0,31,28,31,30,31,30,31,31,30,31,30,31, 0,31,29,31,30,31,30,31,31,30,31,30,31 ;int y, m, d; scanf(“%d%d%d“, ,Example9_4.3: modify the example9_2.4 by using pointer.,Example9_4.6,Pointer Arrays (指针数组),Since pointers are variables themselves, they can be st
35、ored in arrays just as other variables can. The array of pointers (or pointer arrays) is a consecutive series of pointers, which themselves are stored in an array. The form:type * array_name constant expression,pa,pa0,integer,For example:int * pa4;,pa1,integer,pa2,integer,pa3,integer,char * week_day
36、8= “Sunday”, “Monday”,“Tuesday”, “Wednesday”, “Thursday”,“Friday”, “Saturday”, NULL ;,Example9_4.4: according to the name of the day, output the corresponding day number by using pointer array.,d,n,e,s,d,a,u,r,s,d,a,y,0,y,0,W,e,T,h,i,d,a,y,0,F,r,t,u,r,d,a,y,0,S,a,n,d,a,y,0,S,u,n,d,a,y,0,M,o,e,s,d,a,
37、y,0,T,u,NULL,week_day0,week_day1,week_day2,week_day3,week_day4,week_day5,week_day6,week_day7,#include char * week_day8= “Sunday“, “Monday“, “Tuesday“,“Wednesday“, “Thursday“, “Friday“, “Saturday“, NULL ;main( ) int i; char string20;printf(“Enter a string: “); scanf(“%s“, string);i = lookup ( string
38、); printf (“No.=%dn“, i ); lookup( char ch ) /* pass char array */ int i, j; char *pc;for ( i=0; week_dayi!=NULL; i+ ) for(pc=week_dayi, j=0;*pc=chj /* find nothing */ ,#include main( ) char * week_day8= “Sunday“, “Monday“, “Tuesday“,“Wednesday“,“Thursday“,“Friday“,“Saturday“,NULL;int day; char *p,
39、*lookstr( );printf(“Enter day: “); scanf(“%d“, ,Example9_4.5: according to the day number, output the day name by using pointer array.,Array pointer is a pointer, which points to an array. The form:Type (* pointer_name) constant expression Example: int ( * pb) 4 ; -Above define a pointer pb, which p
40、oints to a one-dimension array. There are four integer elements in this array.,Array Pointers (数组指针),integer,pb,(*pb) 0,integer,(*pb) 1,integer,(*pb) 2,integer,(*pb) 3,Example9_4.6: modify the example9_2.4 by using array pointer.,main( ) static int day_tab213 = 0,31,28,31,30,31,30,31,31,30,31,30,31,
41、 0,31,29,31,30,31,30,31,31,30,31,30,31 ;int y, m, d; scanf (“%d %d %d“, ,Example9_4.3,Compare examples :,Three examples use the same array declaration:static int day_tab213 = 0,31,28,31,30,31,30,31,31,30,31,30,31,0,31,29,31,30,31,30,31,31,30,31,30,31 ; Three examples use the same arguments (or same
42、the header of function definition):day_of_year (day_tab, year, month, day),The difference is parameter (day_tab):Example9_2.4: int day_tab 13;Example9_4.3: int * day_tab ;Example9_4.6: int (* day_tab) 13;,0,0,In example9_2.4: int day_tab 13;,-parameter day_tab is a two-dimension array.,In example9_4
43、.3: int * day_tab ; -parameter day_tab is a pointer, which points to the integer data.,31,0,31,28,31,30,31,30,30,31,30,31,31,31,0,31,29,31,30,31,30,30,31,30,31,31,1,0,3,2,5,4,7,6,9,8,11,10,12,0,1,31,31,29,31,30,31,30,30,31,30,31,31,31,31,29,31,30,31,30,30,31,30,31,31,day_tab,day_tab+13,被调用函数使用二维数组形式
44、引用主调函数中数组元素: day_tabij,被调用函数使用指针形式引用主调函数中数组元素: ( * (day_tab+i*13+j) ),-parameter day_tab is an array pointer, which points to an array in where there are 13 integer elements.,In example9_4.6: int (* day_tab) 13;,31,0,31,28,31,30,31,30,30,31,30,31,31,31,0,31,29,31,30,31,30,30,31,30,31,31,1,0,3,2,5,4,
45、7,6,9,8,11,10,12,day_tab,day_tab+1,被调用函数使用数组指针形式引用主调函数中数组元素: (* (day_tab +i) j,Outside the TC environment, there is a way to pass command-line arguments (or parameters) to a program when it begins executing. When main is called, it is called with two arguments.int main (int argc, char *argv ),Comman
46、d-line Arguments (命令行参数),Argc ( for argument counter) is the number of command-line arguments the program was invoked with. Argv (for argument vector) is a pointer to an array of character strings that contain the arguments, one per string.,argv,.,file_name,first argument,n-th argument,argc = n+1,ar
47、gv0,argv1,argvargc-1,The command form:execution_file_name argument_1 argumet_n,Command-line Arguments (con.),Compare differences between two examples.,#include main (int argc, char *argv ) int i;printf (“argc=%dn“, argc);for ( i=0; iargc; i+ )printf(“%sn“, argvi ); ,#include main (int argc, char *ar
48、gv ) int i;printf (“argc=%dn“, argc);for ( i=0; iargc; i+ )printf(“%sn“, *argv + ); ,Example9_4.7: using array,Example9_4.8: using pointer,Request storage function: malloc() Rather than allocating from a compiled-in fixed-sized array (such as int a100), function malloc will request space from the op
49、erating system as needed. The form: void * malloc (unsigned size) - returns a pointer to space for an object of size size, or NULL if the request cannot be satisfied. - this return pointer points to the void type, however, the pointer will take the explicit type conversion according to the actual object type.,