1 / 56

Chapter 9 Pointer

Chapter 9 Pointer. PROGRAMMING IN C. . . . 0000 0000 0000 0100 0000 0000 0000 0111 . . . 00000000 11001100. 2000 2001 2002 2003 3010 3011. memory user data region. 9 . 1 The concept of the pointer and pointer variable. Pointer is address address

sef
Download Presentation

Chapter 9 Pointer

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 9Pointer • PROGRAMMING IN C

  2. . . . 0000 0000 0000 0100 0000 0000 0000 0111 . . . 00000000 11001100 . . . 2000 2001 2002 2003 3010 3011 memory user data region 9 . 1 The concept of the pointer and pointer variable Pointer is address address 1. the address of the memory storage unit ──the serial number of the storage unit

  3. . . . 4 2 7 9 . . . 2004 . . . memory user data region variable k variable m variable i variable j variablei_pointer 2000 2002 2004 2006 3010 2. Variable address and value (1)variable address── The addressof a variable is itself data that can be manipulated and stored in memory (2)value——can be stored in memory

  4. How does the compiler process variable definition ? main() { int num; scanf("%d",&num); printf("num=%d\n", num); } C compiler does operate as follows when it compile variable definition statement ” int num”: (1) distribute variable memory space (2) login variable num to "symbol table" each variable in symbol table contains two attribute: 1) variable name(id) 2) its address (addr) variable address

  5. . . . 4 2 7 9 . . . 2004 . . . Memory user data region Variable k Variable m Variable i Variable j Variablei_pointer 2000 2002 2004 2006 3010 3. The access of variable value (1)Direct access scanf(”%d”,&m); printf(”%d”, m); m=m+i; (2) indirect access visit variable valuethrough another variable (a pointer variable) Example: define a pointer”i_pointer” i_pointer=&i ; scanf(“%d”,i_pointer);

  6. p1 i 9 . 2 Pointer variable points to a variable The definition of pointer variable general format: base-type*pointer-variable ; where:base-type is the type of the value to which the pointer points pointer-variable is the variable being declared for examples, int *p1; char *p2; using a pointer variable 1. assignment of a pointer variable value ( to assign an address to a pointer) for example, int *p1,*p2, i; p1=&i; p2=p1; p2

  7. After definition After p=&i after *p=3 after j=*p+2 : : : : 1000 1002 1004 1000 1002 1004 i j p i j p 1000 1002 1004 i j p 3 1000 1000 1002 1004 3 5 1000 1000 2.toassign a value to a variable with pointer variable “*”:pointer operator、indirection operator is an unary operator(value-pointed-to) for example ,int i , j , *p; p=&i; *p=3; //namely i=3; j=*p+2; i j p Pointer variable must be assigned a value before it is used ,or it becomes a hanging pointer!

  8. operator & and *: (1)associativity :from right to left if:int a, *p1; p1=&a; then: &*p1 =&(*p1)=&(a)=&a=p1 *&a =*(&a)=a (2)priority * prior to &

  9. 3.”--”and “++”operator mostly apply to arrays’ pointer if :float x,*p1; p1=&x; if p=1000, then p++ is 1004 example: int a,b,*p; p=&a; a=3; b=5; (*p)++; the equivalence is a++ a==4 *p++; the equivalence is *(p++) if p=1000, then p++ is 1002

  10. [9.1]The indirect access of variables main() { int a,b; int *pointer_1, *pointer_2; a=100;b=10; pointer_1=&a; /*to assign a’s address to pointer_1*/ pointer_2=&b;/* to assign b’s address to pointer_2*/ printf (”%d,%d\n”, a,b); printf(”%d,%d\n”, *pointer_1,*pointer_2); } The results: 100, 10 100, 10 pointer1 a(*pointer1) &a 100 pointer2 b (*pointer2) &b 10

  11. [9.2]Input two integers a and b ,output them ordered by value . main() { int *p1,*p2,*p, a, b; scanf ("%d%d",&a,&b); p1=&a; p2=&b; if (a<b) {p=p1;pl=p2;p2=p;} printf ("\na=%d,b=%d\n”,a,b); printf("max=%d,min=%d\n",*pl,*p2); } results: 5 9  a=5,b=9 max=9,min=5 if(*p1<*p2)

  12. p1 p1 a a p p &a &b 5 5 p2 p2 b b &a &b 9 9

  13. Analyse program as follows: main() { int *p1,*p2,p; int a,b; scanf("%d%d",&a,&b); p1=&a; p2=&b; if (*p1<*p2) { p=*p1;*p1=*p2;*p2=p;} printf("\n a=%d,b=%d\n",a,b); printf("max=%d,min=%d\n",*p1,*p2); } question:1.analyses function result 5 9  a=?,b=? max=?,min=? 2.how about add three *before p?

  14. a b 3 6 3 6 p1 p2 4.pointer variable act as function parameter question:can the swap function able to realize two variable exchange? void swap(int p1,int p2) { int t; t=p1; p1=p2; p2=t; } main() { int a,b; printf("a,b="); scanf("%d%d",&a,&b); swap(a,b); printf("a=%d,b=%d\n",a,b);}

  15. a b 3 6 &a &b p1 p2 [9.3] pointer variable act as function parameter void swap(int *p1,int *p2) { int t; t=*p1; *p1=*p2; *p2=t; } main() { int a,b; printf("a,b="); scanf("%d%d",&a,&b); swap(&a,&b); printf("a=%d,b=%d\n",a,b); } Transfer value(address)

  16. Summary: We must use pointer variable as function parameter to return the alternative value to calling function from called function Mechanism: When system execute the called function , if the formal parameter pointer variable changes, the value is saved via actual parameter at the end of the function call.

  17. [9.4] Input three integer ,then output them in descending order that realized by using pointer as real parameter. void swap(int *p1, int *p2) { int t; t=*p1, *p1=*p2, *p2=t; } /*design a function to sort three numbers*/ void sort(int *p1,int *p2,int *p3) { if( *p1 < *p2 ) swap( p1, p2 ); if( *p1 < *p3 ) swap( p1, p3 ); if( *p2 < *p3 ) swap( p2, p3 ); }

  18. main() { int n1,n2,n3; printf("Input three numbers:"); scanf("%d%d%d", &n1, &n2,&n3); sort(&n1,&n2,&n3); printf("sort numbers:%d,%d,%d\n",n1,n2,n3); } The results: Input three numbers: 2 1 3  sort numbers:3 2 1

  19. 9.3 Pointer points to an array 1. summarization • conception int a[5]; Array ‘s pointer (head address),array name a element’s pointer (address): a or &a[0] a+1 or&a[1] a+2 or&a[2] a+3 or&a[3] a+3 or&a[4] element value (name) a[0] or *(a+0) a[1] or *(a+1) a[2] or *(a+2) a[3] or *(a+3) a[4] or *(a+4)

  20. For example, int a[5], *p=a (or *p=&a[0]); element’s pointer: p or&p[0] p+1or&p[1] p+2or&p[2] p+3or&p[3] p+3or&p[4] Array element(name) p[0] or *(p+0) p[1] or *(p+1) p[2] or *(p+2) p[3] or *(p+3) p[4] or *(p+4) • Declare a pointer of one-dimensional array instruction:int a[5], *p=a (or&a[0]); namely: int a[5], *p; p=a;

  21. Quoting one-dimensional array element element value element address Subscript method: a[i]&a[i]visual Pointer method :*(a+i)a+i *(p+i)p+i object program occupys memory fewer and run fast. • The difference between p and a: a: address constant p: address variable

  22. Second :array name main() { int a[10], i; printf(“Input 10 ...: ”); for(i=0; i<10; i++) scanf(“%d”, a+i); printf(“a[10]: ”); for(i=0; i<10; i++) printf(“%d”, *(a+i)); printf(“\n”); } [9.5] The quotation of array ‘s elements First:subscript method main() { int a[10], i; printf(“Input 10 numbers: ”); for(i=0; i<10; i++) scanf(“%d”, &a[i]); printf(“a[10]: ”); for(i=0; i<10; i++) printf(“%d ”, a[i]); printf(“\n”); } results: Input 10 numbers: 0 1 2 3 4 5 6 7 8 9←┘ a[10]: 0 1 2 3 4 5 6 7 8 9

  23. four:pointer variable ++ main() { int a[10], *p; printf(“Input 10 ... : ”); for(p=a; p<a+10; p++) scanf(“%d”, p); printf(“a[10]: ”); for(p=a; p<a+10; p++) printf(“%d ”, *p); printf(“\n”); } third:pointer variable main() { int a[10], i, *p=a; printf(“Input 10 ... : ”); for(i=0; i<10; i++) scanf(“%d”, p+i); printf(“a[10]: ”); for(i=0; i<10; i++) printf(“%d ”, *(p+i)); printf(“\n”); } pay attention to the difference betweenp+1 and p++!

  24. 2. Arrays act as parameters of function array name: formal parameter :receive actual parameter’s starting address actual parameter: Transfer the array ‘s starting address to formal parameter When arrays and arrays’ pointers act as function parameters ,there are four equivalence forms(essentially one form ): (1)Both formal parameters and actual parameters are all array names. (2)Both formal parameters and actual parameters are all pointer variables. (3) Actual parameters are pointer variables,formal parameters are array names. (4)Formal parameters are pointer variables,actual parameters aree array names.

  25. a[0] a[1] a[2] a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] 1.1 3.2 5.1 7.3 2.5 4.6 7.8 8.8 4.5 6.7 3.9 2.6 Two –dimensional array‘s pointer: example: int a[3][4]; 3. Two-dimensional array’s pointer row pointer secondary pointer a a+0 a+1 a+2 column pointer firstlevel pointer

  26. discription:two_dimentional array has some features : • array name “a”stands for the starting address and a row pointer that controls a line. a+i:row pointer ,points to line i *(a+i)or a[i]: col pointer ,pointer to line i column 0 • the format of how to access a[i][j] with pointer. a[i][j] *(a[i]+j) *(*(a+i)+j) (*(a+i))[j]

  27. analyses: • a[i]+j:column pointer points to array element a[i][j]. • *(a[i]+j): the value of array element a[i][j] . • If int a[3][4], *p=a[0]; so p+1point to ? how to use p as pointer to access a[i][j]?

  28. 4.Row pointer variable ─a pointer variable points to an one-dimensional array consists of N elements definition form data type (* row pointer variable) [n]; notice:() indispensability,or it becomes pointer array (sixth section introduce). assign a value row pointer variable= two dimensional array name| row pointer variable;

  29. [9.6] Using row pointer and column pointer to output any elements in the two _dimentional array. • using row pointer variable: main() { int a[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}}; int (*p)[4], row, col; p=a; printf(“Input row = ”); scanf(“%d”, &row); printf(“Input col = ”); scanf(“%d”, &col); printf(“a[%d][%d] = %d\n”, row, col, *(*(p+row)+col));} results: Input row = 1←┘ Input col = 2←┘ array[1][2] = 7 reflect:we can also use array name A as pointer, how to modify the program?

  30. using column pointer main() { int a[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}}; int *p, row, col; p=a[0]; printf(“Input row = ”); scanf(“%d”,&row); printf(“Input col = ”); scanf(“%d”,&col); printf(“a[%d][%d]=%d\n”, row,col, *(p+(row*4+col))); }

  31. Two-dimensional array’s pointer acts as function parameter There are two formswhen two-dimensional array’s pointer acts as actual parameter ,column pointer and row pointer. Corresponding formal parameter must use corresponding formal pointer variable: actual parameter: column pointer row pointer ↓ ↓ formal parameter:(column)pointer variable row pointer variable

  32. 5. The realization of the dynamic array static array: The size of the array during the program executing can not be changed. disadvantage: waste the memory space if we can not to estimate the quantity of sata dynamic array: Specify the size of the array according to actual requirement during the program executing. In c language,we canrealize the dynamic array by using array’s pointer act as array name and library functions that apply or release memory.

  33. dynamic array‘s essence:one pointer points to an array [9.7] The realization of the dynamic array #include “alloc.h” #include “stdlib.h” main() { int *array=NULL, num, i; printf(“Input the number of element: ”); scanf(“%d”, &num); /*blockmemory used as application dynamic array */ array=(int *)malloc( sizeof(int) * num ); if ( array==NULL ) /* applyingmemory spaceis failed:prompt,exit.*/ { printf(“out of memory, press any key to quit……”); exit(0); /*exit():terminate running,return Operating System*/ }

  34. printf(“Input %d elements: ”, num); /*prompt to input the number of integer*/ for (i=0; i<num; i++) scanf(“%d”, &array[i]); /*prompt to output the number of integer*/ printf(“%d elements are: ”, num); for (i=0; i<num; i++) printf(“%d,”, array[i]); printf(“\b ”); /*delete the last one data rear separator“,”*/ free(array); /*release the memory block from the application of malloc() function*/ } results: Input the number of element: 3←┘ Input 3 elements: 1 2 3←┘ 3 elements are: 1,2,3

  35. program description: array=(int *)malloc( sizeof(int) * num ); statement ──malloc() function andsizeof operator • library function malloc() usage:void *malloc(unsigned size) function:distribute 1series space in the dynamic storage area of the memory which length id size return value:if application is success ,return the starting address ,if not return NULL。 ·function prototype alloc.h,stdlib.h。 Malloc () returns a typeless pointer and it can points to any type data in order to void mistakes we must transfer the return value into the data type that points to .

  36. operator sizeof form:sizeof(variable name /type name ) function:calculate the space variable/type occupy.e.g,in IBM-PC sizeof(int)=2 • free(array);statement ──library function free() usage:void free(void *ptr) function:release the memory block ptr points to. return value:null In principle,we use malloc () function to apply for MB and use free() function to release the MB after operation.If we release the MB out of time ,it may exhaust systemic memory resource soon , thereby the program can not run .

  37. reflect: (1)use sizeof(int) to calculate the memory byte number that int number ocuppy , why not to use constant 2? (2)scanf(“%d”, &array[i]); printf(“%d,”, array[i]); Pointer points to array acts as array name it must be used according to the syntax rule of quoting array elements. (3) printf(“\b ”);statement

  38. 9.4 character string 'pointer and pointer to character string quote express character string 'pointer : the character string ‘s starting address 9.4.1 The denotation and quotation of character string character array quote character one by one character pointer variable whole quote quote character one by one [9.8] use character pointer variable to express and quote character string . main() { char *string=”I love China”; for(; *string!=’\0’; string++) printf(“%c”, *string); printf(“\n”); } results: I love China

  39. I l o v e C h i n a \0 I l o v e C h i n a \0 string:character pointer variable Description : 1、 char *string="I love China"; definition and initialization string:string =the starting address of character contants amount to :char *string; string=“I love China”; string 2、 differ from character string char str[ ]=“I love China” str[0] str[7] str str=“I love China’’错误

  40. I l o v e C h i n a \0 2.Whole quotation [9.9] use whole quotation and modify[9.8]。 main() { char *string=”I love China”; printf(“%s\n”,string); } whole quote theory:first of all output the first directional character pointer automatic plus 1point the next characterreduplicate the above process until counter with character string closing flag string Notict :none but character arrays and can output the whole elements with one time by using array name 3. The comare of the character pointer variable and character array( (1)memory contents differ (2)assign value mode differ (3)character pointer value could modify,but array name not

  41. 10.4.2 string pointer act as function parameter [9.10] use function call mode and copy character string void string_copy(char *str_from, char *str_to) { int i=0; for(; (*(str_to+i)=*(str_from+i))!=’\0’; i++) ;/*loop body is blank statement*/ } main() {char array_str1[20]=”I am a teacher.”; char array_str2[20]; string_copy(array_str1, array_str2); /*array name is real parameter*/ printf(“array_str2=%s\n”, array_str2); } results: I am a teacher.

  42. 9.5return pointer valued at function one function could return one int type、float type、char type and can return one pointer type 'data Format as follows: function type * function name ([formal parameter table])[9.11] some logistic melt three term competition educate have got three individual,hunt thereinto at least has one term grade unfit out in. require that use pointer function realize./*************************************************************//*seek() function:Estimation whether have got disqualification grade*//*formal parameter: point to 3 int type elementary composition ' 1 dimensional array ' line pointer variable*//*return value:(1) the one (column) pointer of the has disqualification grade,then return point to one's own profession begin column; *//* (2) have no disqualification grade,return value for point to next row 'one (column) pointer*//*************************************************************/

  43. int *seek( int (*pnt_row)[3] ) { int i=0, *pnt_col; /*define a column pointer pnt_col */ pnt_col=*(pnt_row+1); /*make pnt_col point to the head of next line (act as flag)*/ for(; i<3; i++) if(*(*pnt_row+i)<60) /*not passed*/ { pnt_col=*pnt_row; /*make pnt_col point to head of current line */ break; /*break out of loop*/ } return(pnt_col); }

  44. /*main()*/ main() { int grade[3][3]={{55,65,75},{65,75,85},{75,80,90}}; int i,j,*pointer; /*define a column pointer pointer */ for(i=0; i<3; i++) /*control each student*/ { pointer=seek(grade+i); /*use row pointer as real parameter,call seek() function*/ if(pointer==*(grade+i)) /*this student at least have one course failed*/ { /*output this student’s code and each grade*/ printf(“No.%d grade list: ”, i+1); for(j=0; j<3; j++) printf(“%d ”,*(pointer+j)); printf(“\n”); } } } [program demonstration] results: No.1 grade list: 55 65 75

  45. program description: (1) Main function.s pointer=seek(grade+i); statement When calling for seek() function,let the value of the real parameter grade+i(line pointer) ,be copied to formal parameter pnt_row(line pointer variable),make the formal parameter pnt_row point to grade array ' beta I row。 (2)in pointer function seek() : 1) pnt_col=*(pnt_row+1); statement *(pnt_row+1) convert line pointer to column pointer,and point to Array grade’sbeta i+1 row beta 0 column,and assign a value to(column)pointer variable pnt_col . 2) if(*(*pnt_row+i)<60) row pnt_row is a row pointer,and point to Array grade’s i row ;*pnt_row make the pointer conversion from line to column, point to Array grade’s i row 0 column; and the value of the *pnt_row+j is still a pointer,it point to Array’s I row j column;*(*pnt_row+j) is a data( The value of Array element of grade[i][j] )。 [Return]

  46. 9.6 pointer array and function main()’s row refer 9.6.1 pointer Array1. conception:the each element of the array are one pointer data。 design to point to multi-character string,approve lead string manipulation all the more convenience,agility . 2. definition pattern data type * array name [element] Notice :the different of line pointer variable definition pattern。 [E.g 9.12] There are several figure bookery,pray in alphabetical order,man and boy output the title of a book。 solution subject require: use sort function finish sort, and make the input/output in main function。 /**************************************************************/ /* function sort() :Ongoing sort towards character pointer array*/ /*formal parameter:name——character pointer array,count——the number of element*/ /*return value:NULL */ /*************************************************************/

  47. void sort(char *name[ ], int count) { char *temp_p; int i,j,k; /*the select sort for the operational development*/ for(i=0; i<count-1; i++) {k=i; for(j=i+1; j<count; j++) if(strcmp(name[k],name[j])>0) k=j; if( k!=i) /*change position*/ { temp_p=name[i], name[i]=name[k], name[k]=temp_p;} } }

  48. main() { char *name[5]={ “BASIC”,”FORTRAN”, ”PASCAL”,”C”,”FoxBASE”}; int i=0; /*use character array as real parameter ,call function sort()*/ sort(name,5); /*output the sorted outcome*/ for(; i<5; i++) printf(“%s\n”,name[i]); } results: BASIC C FORTRAN FoxBASE PASCAL

  49. program description: (1)the transmission by value of the real parameter versus formal parameter sort( name , 5 ); ↓ ↓ void sort(char *name[], int count) (2)The compare can but use strcmp () function of the character string. Each element of the formal parameter character pointer array name is a pointer to character string .so that strcmp(name[k],name[j])

  50. 9.6.2 The formal parameter of the main function main () Main function main () use format with no arguments in former program. Actually main function main () can appoint formal parameter. [9.13] Realize documentary encryption and decryption in one program. stipulation: The name ofprocedural executable file name is lock.exe. usage:lock +|- <the processed filename>, “+”is encryption,“-”is decryption 。 /*program frnction:Take main function with argument for example. */

More Related