Pointers & Arrays CS2023 Winter 2004
Outcomes: Pointers & Arrays C for Java Programmers, Chapter 8, section 8.12, and Chapter 10, section 10.2 Other textbooks on C on reserve After the conclusion of this section you should be able to Identify how pointers and array are similar and how they are different Use pointers to traverse C arrays (1D and 2D) and pointer subtraction to count how many elements have been traversed Use pointers to pass portions of C arrays to functions
Arrays and Pointers A single-dimensional array is a typed constant pointer initialized to point to a block of memory that can hold a number of objects. is an pointer that points to a block of memory that can hold 1000 integer objects is a pointer to.
! Arrays and Pointers When an array is declared, compiler allocates enough contiguous space in memory to contain all the elements of array Base address of array is address of first element of array. Say bytes numbered 300, 304, 308,..., 696 are alocated as addresses of a[0], a[1],... a[99] is equivalent to Causes 300 to be assigned to p " 0 1 2 3 4 5... 99
# ' %& $ ( # $*, ( -, ( # /. Arrays Assignment and Pointers Can access first element of an array using: )+* or through pointer: ) * Can access other elements of a using pointer arithmetic 0 0 1 2 3 4 5... 99
Pointer Arithmetic Valid operations on pointers include: - the sum of a pointer and an integer - the difference of a pointer and an integer - pointer comparison - the difference of two pointers.
1 2 3 4 2 4 2 1 2 Sum of Pointer and Integer To access other objects in the block of memory pointed to, use where is an integer. This expression yields a pointer to the n-th object beyond the one that currently points to. The exact meaning of "object" is determined by the type of.
7 8? > @ A? @ E C? @ : C @ I H G J Sum of Pointer and Integer => ; < 9:? 8 D A D E? F M K I L K I 5 6 = > B > = B > =
RS T P Q Z V b ] \ Q X Z [ a c ^ Z [ e b ^ \ X [ Y Z d a c _ Z [ e _ [ \ X Z a f d c ` Z [ Sum of Pointer and Integer WY WX U V N O WX 0 1 2 3 4 5 6 7 8 9 W Y 0 1 2 3 4 5 6 7 8 9 b WX 0 1 2 3 4 5 6 7 8 9
t m u n m yz i o s { ƒv Sum of Pointer and Integer: ith object v w prq n o m gh hx k x l lk j ji }~ j h or v are equivalent. and
Š Œ œ Ÿ ž œ œ Š š š Œ ² ± Ž«œ µ Sum of Pointer and Integer: ith object Ž ˆ Ž š ˆ œ Ž Š Ÿ Š Œ Ÿ Š Ž Ÿ ª ³ Ž œ Ÿ š
¹ º Difference of Pointer and Integer Often, we need to access objects preceding the object pointed to by a pointer yields a pointer to the n-th object before the one that currently points to.
À Á ½ ¾ Ç Ã Ï Ê É ¾ Å Ç È Ñ Ð Ë Ç È Ó Ö Í Õ Å È Æ Ç Ò Ì Ô Î Ç È Û Î Å Ç Ú Ø È Ì Ù Í Ç È Difference of Pointer and Integer ÄÆ ÄŠ û ¼ ÄÅ 0 1 2 3 4 5 6 7 8 9 Ä Æ 0 1 2 3 4 5 6 7 8 9 Ü ÄÅ 0 1 2 3 4 5 6 7 8 9
Example Ý Þàß áâ ßã äå çæ è â ã é êìë í êìî í ï ð äå çæ ñóò ë ô ïò õ ö ê â ã â é â ï â ø ß é ùàß ú àû ü ý ê ö ö ê û þ é ë þ é â ã ßÿ ß ÿ ß û ÿ Þàß ÿ ê ö á û ÿ â ô í î ô ë äå çæ ò â äå çæ ò â ë ÿ â ã é á á ã í ê î â ò è
! '& $% # " Careful! Given a block of memory of you can set objects, pointed to by to point to the last object in the block using:, rather than ( off by one error).
* ) ( +, Pointer Comparison Two pointers of the same type, and, may be compared as long as both of them point to objects within a single memory block Pointers may be compared using the <, >, <=, >=, ==,!= When you are comparing two pointers, you are comparing the values of those pointers rather than the contents of memory locations pointed to by these pointers
21 3 0 7?> ; U E E E TS K J P D D AB D M F G V K J AB D F V V K D U E E E TS ^ P D D ] _ K D W G P P Pointers and traversals Assuming 8:9 4 5 465 -/. doubles: <= pointing to an array of and QR LNM H:I C/D B @:A D O D F E M V D H I H/\ B Y Z:[ J X/Y E/W B L M QR C/D B @:A M D F D F ] ] U M E @ ` _C @ V D E/W B
m d d d c lk g h ba f f e pq Block Traversal Idiom ij h h p p o n
r s w ~ {z { w Œ Ž s s ~ Ž ƒ ƒ ƒ ~ z Ž s ~ ~ s ~ {z uz Example: largest element ƒ { } u }~ u w rs ~z z { u u w u z wyx tvu ƒ{ } u ˆ x w u z }~ Š ƒ { } u ˆ x ƒ } u ˆ x { ƒ s ƒ ƒ w x
œ ž ± Example: block copy of Copy the contents of a block (or array) pointed to by size to another block pointed to by : š :ª 6 6 Ÿ/ ««Ÿ/ ª µ ª ³ ² ª 6
¹» º ¾ ¼ ½ À Á Ç ÆÅ Ã Â Ï Ë Ê É Pointer Subtraction Given two pointers, and, such that: both pointers are of the same type, > both point to objects in a single memory block, the expression yields the number of objects between including the object pointed to by. and The type of the result of pointer difference is defined in. Ë/Ì Í Î, ÃyÄ Ç È,
Ò Ó Ø è Ú Ý é ß Þ Ó Û Ü Ý ç áâ Ò Ú Ú Û Ü æ Ø Pointer Subtraction Ø Ö ÔÕ Ü Ù6Û Ù6Ú Ð/Ñ ê Ü Ó 0 1 2 3 4 5 6 7 8 9 ã å ãä Ð Ñ à Output: 3
ë ò ï õ ôó ï óö ò ï ï ï ï ó ó ó ö ó ö ûÿ ï ò ï õ ôó ó ó Example in a block of Find the first occurrence of the value integers ( if not found): íî ì ï ô ðö ò ïñð óùø ò ïñð ú ÿ ïþý ü ïñû ïñð ó ú ö ó ô ï ó ï ï ó ö ó ï ô ð
! F F " # # + E D C G " 76 0 /. 2 1 = 3 L OJ # 0. ; " : B " 3 => 0 1!? in a block of H IJK LNM A@ Example Find the first occurrence of the value integers ( if not found): " %$ & #, *) ( ' # & - - - 8 3 3 45 3 " 8 9 1 1 '+ / 7 < 8 76 45 3 1 1
]\ YX PW S a` S ^ c U ^ Z[ UT V b ]\ YX Ph S S ^ c ^ Z[ UT V b Arrays as Parameters When arrays are used as function parameters, they are actually treated as pointers. The following two declarations are equivalent: feg Ped PRQ PRQ f g P d PRQ i U PRQ The second parameter is necessary to specify the size of the array.
jlk m on p qr n n ps t jlk m u wv x j k m y j{z o } j k m ~ j{ {ƒ n t j u j j y j{z o j j t y kp ˆt ˆq x j Š on mœ kn Ž on mœ kn ƒ j q n jlk m r n n ps t j k m u wv x jlk m y j z o } j k m ~ j{ {ƒ n t j u j j y j{z o j n jlk m t ˆq x ~ j
š œ š Ÿž ž ž ž ž ž Ÿ Ÿ š ª lÿ «{ Ÿž ž ž ± ² ² ± ³ µ ¹lº» ¼ ½¾ À Á Âà ÅÄ Æ ¹lº» ¼ ½¾ À Á Âà ÅÄ Ç È É Æ ÊË Ì Í ¹{Î Ë Ê ¹lº» ¼ ½¾ À Ï Ð Á Âà ÅÄ Ç Ð Æ ÊË ÑÒ Í Í ¹ Î Ë Ê ¹lº» ¼ ½¾ À Ï Ð Á Ó Æ ÊË Ñ ÔÌ Õ ºÌ» Ë Ê
Ö Ø Are Arrays and Pointers Interchangeable? Array parameters are interchangeable with pointer parameters, but array variables are not the same as pointer variables. C compiler converts name of an array to a constant pointer when necessary sizeof(array) returns number of bytes occupied by array, whereas sizeof(pointer) returns number of bytes used to store pointer
ÜÙ Û Û è á ÿ þ ûü ïð ò ñë îí úù Are Arrays and Pointers Interchangeable? àeá ß ß ß ÝÞ ÙRÚ Üé Ûçæ Ù Ú å âäã ÙRÚ Rý eø ö ôõ ô ô ó is ëeì ê is the number of bytes used to. store a pointer to an
" # - 3 +*, 0. +*, 3 0 / ) 8 65 65 7 7 Pointers & Multi-Dimensional Arrays example: & ( $' & $%! 12 0 1 2 3 4 5 14 Arrays stored in row-major order 0 1 2 3 4 5 9
BA BA = > C C = NR NM Z U BA @ X NM M NM NM O O V C S S U Z S BA @ X NR NR M NR V C? NR NM > O V [ ^ b m qp qp e b g n g r r } ` l g m y Pointers & Multi-Dimensional Arrays HLK G EJ I?@ H G EF D?@ :<; S K :<; OQP G K EF D Y Y O W K T N G K EJ I Y Y W K T N H S? H W K as a one-dimensional array of integers: View _a` \<] t{ z ko m y tu s ko kl m kl v w vxw h i hji f ` cld ` b _a` b
~ Š Ž œ š Pointers & Multi-Dimensional Arrays Point to row in array : ƒa < Š jˆ or: L Œ since is the th row of contrast with single-dimensional array where to žÿ equivalent
««µ Á «ª À ¼ ¾ ¾ Æ ÅÄ Ã Ç È ÑÒ Ô ÞÝ Ü ÛÚ Ï ÎÍ ÌË Ó ÎÍ ÌË Ð Õ Õ Pointers & Multi-Dimensional Arrays : of array Clear row L¹ ² µ ± ³ ª ² ± ª a < < ³ ² À À ± ¹ ² ¹ ½ ºL»  ¹ a Can pass to a function that is expecting a onedimensional array as its argument. Find largest element in row of : álâ à ß Ø Ù Ò Ö Ê Ï É<Ê É<Ê
ã é çè é çè ê îï ë Pointers & Multi-Dimensional Arrays Caution: The base address of a two-dimensional array, not. äæå The array name by itself is equivalent to ìæí is ð
õø õö ó ô ÿ ÿ üý û úõ ñ õ þ ô Storage Mapping Function ù ñò is equivalent to Note that column size is required in storage mapping function, which is why it must be specified in function declaration