中国高校课件下载中心 》 教学资源 》 大学文库

英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 10 - Basics of Pointers

文档信息
资源类别:文库
文档格式:PDF
文档页数:3
文件大小:94.42KB
团购合买:点击进入团购
内容简介
英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 10 - Basics of Pointers
刷新页面文档预览

Lecture 10BasicsofPointers.Pointers areavery importantpartofC.InCweneedthemformanytaskse.g.arrays,functions,strings etc·Peopletendtofindpointershardtograsp at first!First lets goback and lookathowntevariablearestored inmemoryDitaSrudasestidcloterynuntergmeraBasicsof PointersBasics.ofPointers&x0nSs102content3815pdan(varistle)Each cell is numbered with asequential address.Wecan alsorefertothembynameD'pointee of p"ThecontentsofeachisacollectionofOs&1swhichcannnimtbe interpreted in different waysSince an address is a number, it too can be stored inApointer is a variable that holds theaddress of another.memoryvariable:Here cell99 contains 102 which is the address ofX We can say that p is a pointer to xWecan saythat"ppointstox-- We could also say that x is the 'pointee of pDeclaringPointerVariablesAddressofOperator&.Wehave seen declarationssuchas intx,y.Sincepointervaluesarereallywhichmeans"xandyarevariablesoftypeaddresses,weneedawaytofindtheint"address ofa variable..We can also declarepointers to alldatatypes·This isdonebythe&operator.e.g.So&xisthe"addressofx".102inourint* p;p is a pointer to an int variableexample.float*zz;zzisapointertoafloat.Note that here*'means pointer and NOT.Thiscanthenbeassignedtopusingmultiplication. Like many operators in C theirp=&x;usage depends upon the context

1 1. Introduction 2. Binary Representation 3. Hardware and Software 4. High Level Languages 5. Standard input and output 6. Operators, expression and statements 7. Making Decisions 8. Looping 9. Arrays 10. Basics of pointers 11. Strings 12. Basics of functions 13. More about functions 14. Files 14. Data Structures 16. Case study: lottery number generator Lecture 10 Lecture 10 Basics of Pointers • Pointers are a very important part of C • In C we need them for many tasks e.g. arrays, functions, strings etc • People tend to find pointers hard to grasp at first! • First lets go back and look at how variable are stored in memory Basics of Pointers 102 38 15 p xy address 98 99 100 101 102 103 104 contents identifier (variable) • Each cell is numbered with a sequential address • We can also refer to them by name • The contents of each is a collection of 0s & 1s which can be interpreted in different ways • Since an address is a number, it too can be stored in memory • Here cell 99 contains 102 which is the address of X • We can say that “p points to x” Basics of Pointers • A pointer is a variable that holds the address of another variable – We can say that p is a pointer to x – We could also say that x is the “pointee” of p &x p “pointer to x” *p=x “pointee of p” Declaring Pointer Variables • We have seen declarations such as int x, y which means “x and y are variables of type int” • We can also declare pointers to all data types e.g. int* p; p is a pointer to an int variable float* zz; zz is a pointer to a float • Note that here ‘*’ means pointer and NOT multiplication. Like many operators in C their usage depends upon the context Address of Operator & • Since pointer values are really addresses, we need a way to find the address of a variable. • This is done by the & operator. • So &x is the “address of x”,102 in our example. • This can then be assigned to p using p=&x;

0it :obs at ene an.InSummary>.PTF*asd,?TTEA"uad,/ declares 2 int variables */w,cn-nd乘int x,yi.1福Eneint*p;/* pointer to an int */*nt"TMR.nEEAR/*p now points to x*/Todp=&x;.neioneo.nW.e:1ou/xisnow13*/*p=13;1n事2.The last line means"setthevalueof the thing<nd n-bmd0shen-e..E.富pointedtobypto 13"-6d2;110gTOPeSince x is what p points to this is equivalent to.01A量saying x=13;推山1-11nouC.NOTE:p=13;setsptopointataddress13,13.W建.3.33quitedifferentanddangerous.BasicsofPointerstinelude cntdio.hsscanfptr.cindfloat mumber.Note that the*and&are complementaryfloat: So *(&x) is x(Parentheses arent actully+needed, evaluation is R to L)&(*p) is pputaafloating poi:ber:") ;:Wevealready seen anexampleof &,in our..-dtG.InlnprintE("To)euseofscanfthing, -/scanf("si", &x);/*input a value for x *TeAeathe.&xisapointertoxandcouldberewrittenasputa('nter a Eloatin)er:")E("tf",int*p-&x;_Pl;scanf("si".p);ArraysandPointersArraysandPointers.Lasttime welooked at arrays.Nowa secret is.Becausearrisactuallyanaddress(typeint)revealedwe can assign its valueto apointer (of typeARRAYSAREREALLYPOINTERSint*).Thus thedeclaration int arr[5]-(65,28,74,22,82];int *ptr;· reserves storage for 5 ints (here 207 to 211)ptr-arr:givesthem values as inthelistor ptr-&arr[0];J* same thing*/ creates a pointer to int called arrWe can referto the3rd int as arr[2] orgives it the value of the address ofthe first int (here 207)*(arr+2) or *(ptr+2) or ptr[2]208209210211address207.We can now seewhy arrayindexes always start74contenl65282282from zero,theyaretheoffsetfrom thenominalnamearr [0]arr[1]arr [2]arr[a]ar[4]addressofthearrayi.e.itsfirstelementshemativ(arr-4)Carr-1)+Er+a)cTT-l2

2 In Summary • The last line means “set the value of the thing pointed to by p to 13” • Since x is what p points to this is equivalent to saying x=13; • NOTE: p=13; sets p to point at address 13, quite different and dangerous int x,y; /* declares 2 int variables */ int* p; /* pointer to an int */ p=&x; /* p now points to x */ *p=13; /* x is now 13 */ /* Example: basics of pointers, & and * operators */ #include main() { int i = 57, j = 19; /* declare two ints */ int *ptr; /* and a pointer to an int */ ptr = NULL; /* constant defined in as 0 Means "not pointing to anything" */ printf("ptr = %p\n", ptr); ptr = &i; /* set ptr to the address of i, i.e. ptr is a pointer to i, and i is the "pointee" of ptr */ printf("ptr = %p\n", ptr); /* We now have two ways of accessing the same variable: */ printf("i = %i, j = %i, *ptr = %i\n", i, j, *ptr); *ptr *= 2; /* same as i = 2 * i; */ (*ptr)-; /* same as i-; */ printf("i = %i, j = %i, *ptr = %i\n", i, j, *ptr); ptr = &j; /* ptr now points at j */ printf("i = %i, j = %i, *ptr = %i\n", i, j, *ptr); *ptr *= 2; /* same as j = 2 * j; */ (*ptr)-; /* same as j-; */ printf("i = %i, j = %i, *ptr = %i\n\n", i, j, *ptr); /* Relationships among the variables: */ printf("&ptr (the address of ptr) is\n%p\n\n", &ptr); printf("ptr (the contents of address %p) is\n%p\n\n", &ptr, ptr); printf("*ptr (the contents of address %p) is\n%i\n\n", ptr, *ptr); printf("&(*ptr) (the address of *ptr) is\n%p\n\n", &(*ptr)); printf("&j (the address of j) is\n%p\n\n", &j); printf("j (the contents of address %p) is\n%i\n\n", &j, j); printf("*(&j) (the contents of address %p) is\n%i\n", &j, *(&j)); } /* Example: basics of pointers, & and * operators */ #include main() { int i = 57, j = 19; /* declare two ints */ int *ptr; /* and a pointer to an int */ ptr = NULL; /* constant defined in as 0 Means "not pointing to anything" */ printf("ptr = %p\n", ptr); ptr = &i; /* set ptr to the address of i, i.e. ptr is a pointer to i, and i is the "pointee" of ptr */ printf("ptr = %p\n", ptr); /* We now have two ways of accessing the same variable: */ printf("i = %i, j = %i, *ptr = %i\n", i, j, *ptr); *ptr *= 2; /* same as i = 2 * i; */ (*ptr)-; /* same as i-; */ printf("i = %i, j = %i, *ptr = %i\n", i, j, *ptr); ptr = &j; /* ptr now points at j */ printf("i = %i, j = %i, *ptr = %i\n", i, j, *ptr); *ptr *= 2; /* same as j = 2 * j; */ (*ptr)-; /* same as j-; */ printf("i = %i, j = %i, *ptr = %i\n\n", i, j, *ptr); /* Relationships among the variables: */ printf("&ptr (the address of ptr) is\n%p\n\n", &ptr); printf("ptr (the contents of address %p) is\n%p\n\n", &ptr, ptr); printf("*ptr (the contents of address %p) is\n%i\n\n", ptr, *ptr); printf("&(*ptr) (the address of *ptr) is\n%p\n\n", &(*ptr)); printf("&j (the address of j) is\n%p\n\n", &j); printf("j (the contents of address %p) is\n%i\n\n", &j, j); printf("*(&j) (the contents of address %p) is\n%i\n", &j, *(&j)); } pointer1.c pointer1.c Basics of Pointers • Note that the * and & are complementary • So *(&x) is x &(*p) is p • Weve already seen an example of &, in our use of scanf scanf(“%i”, &x); /* input a value for x */ • &x is a pointer to x and could be rewritten as int*p=&x; scanf(“%i”,p); (Parentheses arent actually needed, evaluation is R to L) /* Example: scanf and pointers */ #include main() { float number; float *number_p; number_p = &number; /* number_p points to number */ /* One way to do it: */ puts("Enter a floating point number:"); scanf("%f", &number); printf("You entered %G.\n\n", number); /* Another way to do the same thing: */ puts("Enter a floating point number:"); scanf("%f", number_p); printf("You entered %G.\n", *number_p); } /* Example: scanf and pointers */ #include main() { float number; float *number_p; number_p = &number; /* number_p points to number */ /* One way to do it: */ puts("Enter a floating point number:"); scanf("%f", &number); printf("You entered %G.\n\n", number); /* Another way to do the same thing: */ puts("Enter a floating point number:"); scanf("%f", number_p); printf("You entered %G.\n", *number_p); } scanfptr.c scanfptr.c Arrays and Pointers • Last time we looked at arrays. Now a secret is revealed ARRAYS ARE REALLY POINTERS • Thus the declaration int arr[5]={65,28,74,22,82}; • reserves storage for 5 ints (here 207 to 211) • gives them values as in the list • creates a pointer to int called arr • gives it the value of the address of the first int (here 207) 65 28 74 22 82 arr[0] address 207 208 209 210 211 contents name arr[1] arr[2] arr[3] arr[4] alternative *arr *(arr+1) *(arr+2) *(arr+3) *(arr+4) Arrays and Pointers • Because arr is actually an address (type int*) we can assign its value to a pointer (of type int*) int *ptr; ptr=arr; or ptr=&arr[0]; /* same thing*/ • We can refer to the 3rd int as arr[2] or *(arr+2) or *(ptr+2) or ptr[2] • We can now see why array indexes always start from zero, they are the offset from the nominal address of the array i.e. its first element

TwoDimensionalArraysand1. iePointersEpe lee we p e上Whenwedeclareint arr[2] [3]-((11,22,33],(44,55,66])-Storage is reserved for 6 intsavalues aregivento themas inthe list oflists- a pointer to a pointer to an int is created called arrORA-its value is set to the address of the first int:roo][0]arr[0o][1]arr[0] [2]mo*co.ION.arr[1]arr [1] [0]arr[1] [1]arr [1] [2]R00 W So arr[0][0] can be referred to as **arr生编发Barr[1][2] can be referred to as (arr[1]+2) or (arr[0]+5)e/ea[ eetaonitsisn u i P E+ ::.新二12.B1npu80TueI.8Houewmo[engeuro. (oipus s minod ww*+ Ipens - awn/odn tns IreI. cm-/ 1e . mr. 一 to1ot.E018 · sA丰3

3 /* Example: pointers and arrays */ #include main() { int arr[5] = {65, 28, 74, 22, 82}; /* declare an array of ints */ int *ptr1, *ptr2; /* and two pointers to an int */ int i; ptr1 = arr; /* set pointer ptr1 to point at the array, i.e. ptr1 contains the address of arr[0], and arr[0] is the "pointee" of ptr1. (Note that arr is itself a pointer.) We could also write ptr1 = &arr[0]; */ ptr2 = &arr[4]; /* set pointer ptr2 to point at the last element in the array, i.e. ptr2 contains the address of arr[4], and arr[4] is the "pointee" of ptr2. */ /* We now have several ways of accessing the same array elements: */ printf("arr[0] is %i, arr[4] is %i\n", arr[0], arr[4]); printf("*arr is %i, *(arr + 4) is %i\n", *arr, *(arr + 4)); printf("*&arr[0] is %i, *&arr[4] is %i\n", *&arr[0], *&arr[4]); printf("*ptr1 is %i, *ptr2 is %i\n", *ptr1, *ptr2); printf("*(ptr2 - 4) is %i, *(ptr1 + 4) is %i\n", *(ptr2 - 4), *(ptr1 + 4)); printf("ptr1[0] is %i, ptr1[4] is %i\n", ptr1[0], ptr1[4]); printf("ptr2[-4] is %i, ptr2[0] is %i\n\n", ptr2[-4], ptr2[0]); /* We can use them in loops, e.g.: */ for (i = 0; i main() { int arr[5] = {65, 28, 74, 22, 82}; /* declare an array of ints */ int *ptr1, *ptr2; /* and two pointers to an int */ int i; ptr1 = arr; /* set pointer ptr1 to point at the array, i.e. ptr1 contains the address of arr[0], and arr[0] is the "pointee" of ptr1. (Note that arr is itself a pointer.) We could also write ptr1 = &arr[0]; */ ptr2 = &arr[4]; /* set pointer ptr2 to point at the last element in the array, i.e. ptr2 contains the address of arr[4], and arr[4] is the "pointee" of ptr2. */ /* We now have several ways of accessing the same array elements: */ printf("arr[0] is %i, arr[4] is %i\n", arr[0], arr[4]); printf("*arr is %i, *(arr + 4) is %i\n", *arr, *(arr + 4)); printf("*&arr[0] is %i, *&arr[4] is %i\n", *&arr[0], *&arr[4]); printf("*ptr1 is %i, *ptr2 is %i\n", *ptr1, *ptr2); printf("*(ptr2 - 4) is %i, *(ptr1 + 4) is %i\n", *(ptr2 - 4), *(ptr1 + 4)); printf("ptr1[0] is %i, ptr1[4] is %i\n", ptr1[0], ptr1[4]); printf("ptr2[-4] is %i, ptr2[0] is %i\n\n", ptr2[-4], ptr2[0]); /* We can use them in loops, e.g.: */ for (i = 0; i main() { int arr[2][3] = {{11, 22, 33}, {44, 55, 66}}; /* an array of ints */ int *ptr; /* a pointer to int */ int i; /* row index */ int j; /* column index */ ptr = &arr[0][0]; /* set pointer ptr to point at the start of the array, i.e. ptr contains the address of arr[0][0], so arr[0][0] is the "pointee" of ptr. We could also write ptr = *arr, because this means &(**arr). Now, **arr means *(*arr), which means *(arr[0]), which means arr[0][0]. We could also write ptr = arr[0]; because ptr is a pointer to int and so is arr[0]: it points to arr[0][0]. We could also write ptr = *arr; because ptr is a pointer to int (type int *) and arr is a pointer to a pointer to int (type int **). */ /* We now have several ways of accessing the array elements. */ /* As a two-dimensional array: */ for (i = 0; i main() { int arr[2][3] = {{11, 22, 33}, {44, 55, 66}}; /* an array of ints */ int *ptr; /* a pointer to int */ int i; /* row index */ int j; /* column index */ ptr = &arr[0][0]; /* set pointer ptr to point at the start of the array, i.e. ptr contains the address of arr[0][0], so arr[0][0] is the "pointee" of ptr. We could also write ptr = *arr, because this means &(**arr). Now, **arr means *(*arr), which means *(arr[0]), which means arr[0][0]. We could also write ptr = arr[0]; because ptr is a pointer to int and so is arr[0]: it points to arr[0][0]. We could also write ptr = *arr; because ptr is a pointer to int (type int *) and arr is a pointer to a pointer to int (type int **). */ /* We now have several ways of accessing the array elements. */ /* As a two-dimensional array: */ for (i = 0; i main() { int i = 57; float ztran4; int track[] = {1, 2, 3, 4, 5, 6}, stick[2][2]; int *nsave; /* Let's try using *nsave as an int variable, and set it to 38 */ *nsave = 38; /* BUG */ nsave = NULL; *nsave = 38; /* BUG */ nsave = 38; /* BUG */ &nsave = 38; /* BUG */ nsave = &i; *nsave = 38; nsave = &ztran4; /* BUG */ nsave = track; /* nsave points at track[0] */ /* Increase track[0] by 1: */ *nsave++; /* BUG */ /* Now point at stick: */ nsave = stick; /* BUG */ nsave = &stick; /* BUG */ nsave = stick[0][0]; /* BUG */ nsave = *stick; /* BUG */ nsave = **stick; /* BUG */ nsave = stick[0]; nsave = &stick[0][0]; nsave = &**stick; } /* BUG ZONE!!! Example: some common pointer errors */ #include main() { int i = 57; float ztran4; int track[] = {1, 2, 3, 4, 5, 6}, stick[2][2]; int *nsave; /* Let's try using *nsave as an int variable, and set it to 38 */ *nsave = 38; /* BUG */ nsave = NULL; *nsave = 38; /* BUG */ nsave = 38; /* BUG */ &nsave = 38; /* BUG */ nsave = &i; *nsave = 38; nsave = &ztran4; /* BUG */ nsave = track; /* nsave points at track[0] */ /* Increase track[0] by 1: */ *nsave++; /* BUG */ /* Now point at stick: */ nsave = stick; /* BUG */ nsave = &stick; /* BUG */ nsave = stick[0][0]; /* BUG */ nsave = *stick; /* BUG */ nsave = **stick; /* BUG */ nsave = stick[0]; nsave = &stick[0][0]; nsave = &**stick; } pointer.bug pointer.bug

已到末页,全文结束
刷新页面下载完整文档
VIP每日下载上限内不扣除下载券和下载次数;
按次数下载不扣除下载券;
注册用户24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
相关文档