43
1 2000 Prentice Hall, Inc. All rights reserved. C h a p t e r 7 - P o i n t e r s 2000 Prentice Hall, Inc. All rights reserved. P o i n t e r s – Powerful, but difficult to master – Simulate call-by-reference – Close relationship with arrays and strings

Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

  • Upload
    vuxuyen

  • View
    228

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

1

2000 Prentice Hall, Inc. All rights reserved.

Chapter 7 - Pointers

��������� ��� �� ������� ����������� ����� � !��� ���#"$��%'&(�)� &+*-, "/.0"1��, &+� &��2� �$��3$&����4�5�6� �7� &(, � 89&��2� ����� : !��� ���#"$��;�<�"$� &-�5��� 3�� = >?&+, , � ��@BA!�6������� ���C3D*FEHGI"1J5"'� "$����"�� K LM3N� ��@��2O�"P>?����3Q��R���&�, � J�� "$��ST� ��OT U�$� ���5"�� 3�� V W��6*-*-, "YXZ��� ��L�3�� �I@[>\&(, ,Z*FEHGI"0J�"�� "$����"�� �� !��� ���#"$�6]Q^�<�� "�3Q3Z� �$�I3$&(���B !��� ���#"$��_`�a� ��O6bc"���� ��� d eIO�"fGC"$, &��7� �$�I3NO6� <[*F"��5Sg"�"$�h !��� ���#"$� 3$&(����_i�a� &-Ej3�� k _i�a� &-Ej3'�1J- !��� ���)"'� 3�� ��F� !��� ���#"$� 3$�5�fAU�6������� �$��3

2000 Prentice Hall, Inc. All rights reserved.

lnmZo pQqcrMs�t/uwvixyr�z5t{q

• Pointers– Powerful, but difficult to master

– Simulate call-by-reference

– Close relationship with arrays and strings

Page 2: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

2

2000 Prentice Hall, Inc. All rights reserved.

lnm}| ~\t�z�qir!��sc����sCz#�w�4�5���y�/x��5��s��4r�z5t�qc���wqcup9q�z�r�z5����z��$�Br�z�t�q

• Pointer variables– Contain memory addresses as their values

– Normal variables contain a specific value (directreference)

– Pointers contain address of a variable that has a specificvalue (indirect reference)

– Indirection - referencing a pointer value

count

7

count Pt r

 

count

7

2000 Prentice Hall, Inc. All rights reserved.

lnm}| ~\t�z�qir!��sc����sCz#�w�4�5���y�/x��5��s��4r�z5t�qc���wqcup9q�z5r�z��w��z5�$�4r�z5t{q��jpQp��

• Pointer declarations– * used with pointer variables

i nt * myPt r ;

– Declares a pointer to an i nt (pointer of type i nt * )

– Multiple pointers, multiple *

i nt * myPt r 1, * myPt r 2;

– Can declare pointers to any data type– Initialize pointers to 0, NULL, or an address

• 0 or NULL - points to nothing (NULL preferred)

Page 3: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

3

2000 Prentice Hall, Inc. All rights reserved.

lnm}� ~\t�z�qir!��sc������s7�Br!t�s7�

• & (address operator)– Returns address of operandi nt y = 5;

i nt * yPt r ;

yPt r = &y; / / yPt r get s addr ess of y

– yPt r “points to” y

yPt r

y

5

ypt r

500000 600000

y

600000 5

Address of yis value ofypt r

2000 Prentice Hall, Inc. All rights reserved.

lnm}� ~\t�z�qir!��sc������s��4r!t�s7���6pQp}�

• * (indirection/dereferencing operator)– Returns a synonym/alias of what its operand points to

* ypt r returns y (because ypt r points to y )

– * can be used for assignment• Returns alias to an object* ypt r = 7; / / changes y t o 7

– Dereferenced pointer (operand of * ) must be an lvalue(no constants)

Page 4: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

4

2000 Prentice Hall, Inc. All rights reserved.

lnm}� ~\t�z�qir!��sc������s7�Br!t�s7���6p�p9p��

• * and & are inverses– They cancel each other out

* &ypt r - > * ( &ypt r ) - > * ( addr ess of ypt r ) - >r et ur ns al i as of what oper and points t o - > ypt r

&* ypt r - > &( * ypt r ) - > &( y) - > r et ur ns addr ess of y,whi ch is ypt r - > ypt r

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

�C �¡1¢�£�¤ ¥j¦�¢`§I¥j¦�¨ ¥j©j¤ ¢Fª«y¬ ­ ¨ ®�¨ ¥j¤ ¨ ¯�¢D§�¥�¦5¨ ¥j©�¤ ¢�ª°  �±I¦5¨ ­ ®

±C¦5²�³�¦5¥�´�µ(¶N®�·j¶N®

1 / * Fi g. 7. 4: f i g07_04. c

2 Usi ng t he & and * oper at or s * /

3 #i nc l ude <st di o. h>

4

5 i nt mai n( )

6 {

7 i nt a; / * a i s an i nt eger * /

8 i nt * aPt r ; / * aPt r i s a poi nt er t o an i nt eger * /

9

10 a = 7;

11 aPt r = &a; / * aPt r set t o addr ess of a * /

12

13 pr i nt f ( " The addr ess of a i s %p"

14 " \ nThe val ue of aPt r i s %p" , &a, aPt r ) ;

15

16 pr i nt f ( " \ n\ nThe val ue of a i s %d"

17 " \ nThe val ue of * aPt r i s %d" , a, * aPt r ) ;

18

19 pr i nt f ( " \ n\ nShowi ng t hat * and & ar e i nver ses of "

20 " each ot her . \ n&* aPt r = %p"

21 " \ n* &aPt r = %p\ n" , &* aPt r , * &aPt r ) ;

22

23 r et ur n 0;

24 }

The addr ess of a i s 0012FF88The val ue of aPt r i s 0012FF88

The val ue of a i s 7The val ue of * aPt r i s 7Pr ovi ng t hat * and & ar e compl ement s of each ot her .&* aPt r = 0012FF88* &aPt r = 0012FF88

The address of a is thevalue of aPt r .

The * operator returns analias to what its operandpoints to. aPt r points to a,so * aPt r returns a.

Notice how * and& are inverses

Page 5: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

5

2000 Prentice Hall, Inc. All rights reserved.

lnm}¸ ¹�������z2qiº¼»(v�qcxyrMz#t�qc�½�[¾À¿g�yÁ9��s���qcx/�

• Call by reference with pointer arguments– Pass address of argument using & operator

– Allows you to change actual location in memory– Arrays are not passed with & because the array name is already a

pointer

• * operator– Used as alias/nickname for variable inside of functionvoi d doubl e( i nt * number )

{

* number = 2 * ( * number ) ;

}

* number used as nickname for the variable passed

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

�C �ÂQ¶ ­ £�®�¨ ² ­ ·j¦�²F®�²F®�ÃZ·F¢Ä ®�¥�Å�¢�ª�¥`·j²F¨ ­ ®�¢�¦N®�²`¥ ­i nt

 �C  � ¬ ­ ¨ ®�¨ ¥j¤ ¨ ¯�¢`§I¥j¦�¨ ¥j©j¤ ¢Fª«  �ÆÇ¥j¤ ¤!È ¶ ­ £�®�¨ ² ­°  �¡1¢�È ¨ ­ ¢iÈ ¶ ­ £F®�¨ ² ­

±C¦5²�³�¦5¥�´�µ(¶N®�·j¶N®

1 / * Fi g. 7. 7: f i g07_07. c

2 Cube a var i abl e usi ng cal l - by- r ef er ence

3 wi t h a poi nt er ar gument * /

4

5 #i nc l ude <st di o. h>

6

7 voi d cubeByRef er ence( i nt * ) ; / * pr ot ot ype * /

8

9 i nt mai n( )

10 {

11 i nt number = 5;

12

13 pr i nt f ( " The or i gi nal val ue of number i s %d" , number ) ;

14 cubeByRef er ence( &number ) ;

15 pr i nt f ( " \ nThe new val ue of number i s %d\ n" , number ) ;

16

17 r et ur n 0;

18 }

19

20 voi d cubeByRef er ence( i nt * nPt r )

21 {

22 * nPt r = * nPt r * * nPt r * * nPt r ; / * cube number i n mai n * /

23 }

The or i gi nal val ue of number i s 5The new val ue of number i s 125

Notice how the address ofnumber is given -cubeByRef er ence expects apointer (an address of a variable).

Inside cubeByRef er ence,* nPt r is used (* nPt r isnumber ).

Page 6: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

6

2000 Prentice Hall, Inc. All rights reserved.

lnm�É ÊY�Ëz�qcºÌr�Íi�ι�t�qc�ÏrhÐ�vc����z5ÁZz5��scÑÒz#rMÍ�~\t�z�qir!��s7�

• const qualifier - variable cannot be changed– Good idea to have const if function does not need to change a

variable– Attempting to change a const is a compiler error

• const pointers - point to same memory location– Must be initialized when declaredi nt * const myPt r = &x;

• Type i nt * const - constant pointer to an i nt

const i nt * myPt r = &x;

• Regular pointer to a const i nt

const i nt * const Pt r = &x;

• const pointer to a const i nt

• x can be changed, but not * Pt r

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

�C �¡1¢�£�¤ ¥j¦�¢`§I¥j¦�¨ ¥j©j¤ ¢Fª�C  �Ó¡0¢�£F¤ ¥F¦#¢

const·�²F¨ ­ ® ¢�¦N®�²`¥ ­i nt

 «  �ÆÇÔN¥ ­ ³�¢

* pt rÕ ÖÇÔN¨ £FÔ\¨ ªx ×  

«   �ÓØ�®�® ¢F´i·�®Z®�²£FÔN¥ ­ ³�¢pt r .

°  �µ(¶N®�·j¶N®

±C¦5²�³�¦5¥�´�µ(¶N®�·j¶N®

1 / * Fi g. 7. 13: f i g07_13. c

2 At t empt i ng t o modi f y a const ant poi nt er t o

3 non- const ant dat a * /

4

5 #i nc l ude <st di o. h>

6

7 i nt mai n( )

8 {

9 i nt x, y;

10

11 i nt * cons t pt r = &x ; / * pt r i s a const ant poi nt er t o an

12 i nt eger . An i nt eger can be modi f i ed

13 t hr ough pt r , but pt r al ways poi nt s

14 t o t he same memor y l ocat i on. * /

15 * pt r = 7;

16 pt r = &y;

17

18 r et ur n 0;

19 }

FI G07_13. c:Er r or E2024 FI G07_13. c 16: Cannot modi f y a cons t obj ect i nf unct i on mai n* * * 1 er r or s i n Compi l e * * *

Changing * pt r is allowed - x isnot a constant.

Changing pt r is an error -pt r is a constant pointer.

Page 7: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

7

2000 Prentice Hall, Inc. All rights reserved.

lnm}Ù ÚYvP�Û�4�5�ÝÜgt�s7ryÊÓ�?z�qcºÌ¹�������Þ��[¾/Þ-s��/ÁQ��s��{qcxy�

• Implement bubblesort using pointers– Swap two elements– swap function must receive address (using &) of array elements

• Array elements have call-by-value default

– Using pointers and the * operator, swap can switch array elements

• PsuedocodeInitialize array

print data in original order

Call function bubblesort

print sorted array

Define bubblesort

2000 Prentice Hall, Inc. All rights reserved.

lnm}Ù ÚYvP�Û�4�5�ÝÜgt�s7ryÊÓ�?z�qcºÌ¹�������Þ��[¾/Þ-s��/ÁQ��s��{qcxy��jp9p}�

• si zeof

– Returns size of operand in bytes

– For arrays: size of 1 element * number of elements– if si zeof ( i nt ) = 4 byt es, t hen

i nt myAr r ay[ 10] ;

pr i nt f ( " %d" , s i zeof ( myAr r ay ) ) ;

will print 40

• si zeof can be used with– Variable names

– Type name

– Constant values

Page 8: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

8

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

�C  ¬ ­ ¨ ®�¨ ¥F¤ ¨ ¯7¢`¥j¦�¦�¥jÃ�C  �Ó¡0¢�£F¤ ¥F¦#¢D§I¥�¦5¨ ¥�©�¤ ¢Fª«  �±I¦5¨ ­ ®�¥j¦�¦5¥jë   �ÓÆÏ¥j¤ ¤

bubbl eSor t

«   « ±I¦5¨ ­ ®Z¥�¦5¦�¥jÃ

1 / * Fi g. 7. 15: f i g07_15. c

2 Thi s pr ogr am put s val ues i nt o an ar r ay, sor t s t he val ues i nt o

3 ascendi ng or der , and pr i nt s t he r esul t i ng ar r ay. * /

4 #i nc l ude <st di o. h>

5 #def i ne SI ZE 10

6 voi d bubbl eSor t ( i nt * , cons t i nt ) ;

7

8 i nt mai n( )

9 {

10

11 i nt a[ SI ZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 } ;

12 i nt i ;

13

14 pr i nt f ( " Dat a i t ems i n or i gi nal or der \ n" ) ;

15

16 f or ( i = 0; i < SI ZE; i ++ )

17 pr i nt f ( " %4d" , a[ i ] ) ;

18

19 bubbl eSor t ( a, SI ZE ) ; / * sor t t he ar r ay * /

20 pr i nt f ( " \ nDat a i t ems i n ascendi ng or der \ n" ) ;

21

22 f or ( i = 0; i < SI ZE; i ++ )

23 pr i nt f ( " %4d" , a[ i ] ) ;

24

25 pr i nt f ( " \ n" ) ;

26

27 r et ur n 0;

28 }

29

30 voi d bubbl eSor t ( i nt * ar r ay, cons t i nt s i ze )

31 {

32 voi d swap( i nt * , i nt * ) ;

Bubbl esor t gets passed theaddress of array elements(pointers). The name of anarray is a pointer.

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

°  �Â�¶ ­ £�® ¨ ² ­Ëß ¢FÈ ¨ ­ ¨ ®�¨ ² ­ ª

±C¦5²�³�¦5¥�´�µ(¶N®�·j¶N®

33 i nt pass, j ;

34 f or ( pass = 0; pass < s i ze - 1; pass++ )

35

36 f or ( j = 0; j < s i ze - 1; j ++ )

37

38 i f ( ar r ay[ j ] > ar r ay[ j + 1 ] )

39 swap( &ar r ay[ j ] , &ar r ay[ j + 1 ] ) ;

40 }

41

42 voi d swap( i nt * el ement 1Pt r , i nt * el ement 2Pt r )

43 {

44 i nt hol d = * el ement 1Pt r ;

45 * el ement 1Pt r = * el ement 2Pt r ;

46 * el ement 2Pt r = hol d;

47 }

Dat a i t ems i n or i gi nal or der 2 6 4 8 10 12 89 68 45 37Dat a i t ems i n ascendi ng or der 2 4 6 8 10 12 37 45

Page 9: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

9

2000 Prentice Hall, Inc. All rights reserved.

lnm9l ~\t�z�qir!��s�à$áH�4s��y���\z5t�qc�â��qiu¼~\t�z�qcr!��sãäsIz5r�Í�å��/r�z�x

• Arithmetic operations can be performed onpointers– Increment/decrement pointer (++ or - - )

– Add an integer to a pointer( + or += , - or - =)

– Pointers may be subtracted from each other

– Operations meaningless unless performed on an array 

2000 Prentice Hall, Inc. All rights reserved.

lnm9l ~\t�z�qir!��s�à$áH�4s��y���\z5t�qc�â��qiu¼~\t�z�qcr!��sãäs�z�r�Í�å��/r�z5x��6pQp}�

• 5 element i nt array on machine with 4 byte i nt s– vPt r points to first element v[ 0]

at location 3000. (vPt r = 3000)

– vPt r +=2; sets vPt r to 3008

• vPt r points to v[ 2] (incremented

by 2), but machine has 4 byte i nt s.

poi nt er var i abl e vPt r

v[ 0] v[ 1] v[ 2] v[ 4]v[ 3]

3000 3004 3008 3012 3016

l ocat i on

 

Page 10: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

10

2000 Prentice Hall, Inc. All rights reserved.

lnm9l ~\t�z�qir!��s�à$áH�4s��y���\z5t�qc�â��qiu¼~\t�z�qcr!��sãäsIz5r�Í�å��/r�z�xæ�6p�p9p}�

• Subtracting pointers– Returns number of elements from one to the other.

vPt r 2 = v[ 2] ;

vPt r = v[ 0] ;

vPt r 2 - vPt r == 2.

• Pointer comparison ( <, == , > )– See which pointer points to the higher numbered array

element– Also, see if a pointer points to 0

2000 Prentice Hall, Inc. All rights reserved.

lnm9l ~\t�z�qir!��s�à$áH�4s��y���\z5t�qc�â��qiu¼~\t�z�qcr!��sãäs�z�r�Í�å��/r�z5x��6p}���

• Pointers of the same type can be assigned to eachother– If not the same type, a cast operator must be used– Exception: pointer to voi d (type voi d * )

• Generic pointer, represents any type• No casting needed to convert a pointer to voi d pointer

• voi d pointers cannot be dereferenced

Page 11: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

11

2000 Prentice Hall, Inc. All rights reserved.

lnm�ç è(Íc��¿`�����Br�z�t�qc�?Í�z��ÌÚ`�ér!Ñê�y��që~\t�z2qir!��s7�â�wq`uãäs�s7�Û¾h�

• Arrays and pointers are closely related– Array name like a constant pointer

– Pointers can do array subscripting operations

• Declare an array b[ 5] and a pointer bPt rbPt r = b;

Array name is actually an address - i.e. address of the first elementOR

bPt r = &b[ 0]

Explicitly assign bPt r to address of first element

2000 Prentice Hall, Inc. All rights reserved.

lnm�ç è(Íc��¿`�����Br�z�t�qc�?Í�z��ÌÚ`�ér!Ñê�y��që~\t�z2qir!��s7�â�wq`uãäs�s7�Û¾h�ì�jp9pí�

• Element b[ n]– can be accessed by * ( bPt r + n )

– n - offset (pointer/offset notation)

– Array itself can use pointer arithmetic.b[ 3] same as * ( b + 3)

– Pointers can be subscripted (pointer/subscript notation)bPt r [ 3] same as b[ 3]

Page 12: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

12

2000 Prentice Hall, Inc. All rights reserved.

lnm}î ãäs�s7�Û¾h�ât/Áï~\t�z�qcr!��s��

• Arrays can contain pointers - array of stringschar * sui t [ 4] = { " Hear t s" , " Di amonds" , " Cl ubs" , " Spades" } ;

– String: pointer to first character– char * - each element of sui t is a pointer to a char

– Strings not actually in array - only pointers to string in array

• sui t array has a fixed size, but strings can be ofany size.

sui t [ 3]

sui t [ 2]

sui t [ 1]

sui t [ 0] ’ H’ ’ e’ ’ a’ ’ r ’ ’ t ’ ’ s ’ ’ \ 0’

’ D’ ’ i ’ ’ a’ ’ m’ ’ o’ ’ n’ ’ d’ ’ s ’ ’ \ 0’

’ C’ ’ l ’ ’ u’ ’ b’ ’ s ’ ’ \ 0’

’ S’ ’ p’ ’ a’ ’ d’ ’ e’ ’ s ’ ’ \ 0’

 

2000 Prentice Hall, Inc. All rights reserved.

lnmNoÏð ¹��B�Ï�ÀÜgr�vcu4¾yñËãò¹���s�uóÜYÍ�viÁQÁN��z�qcºÌ��qcu�y�/����z2q`ºÌÜÓz�åÌvP�#�4r�z5t�q

• Card shuffling program– Use array of pointers to strings

– Use double scripted array (suit, face)

– The numbers 1-52 go into the array - this is the order they are dealt

Hear t s

Di amonds

Cl ubs

Spades

0

1

2

3

Ace Two Thr ee Four Fi ve Si x Seven Ei ght Ni ne Ten Jack Queen Ki ng0 1 2 3 4 5 6 7 8 9 10 11 12

deck[ 2] [ 12] r epr esent s t he Ki ng of Cl ubs

Cl ubs Ki ng

Page 13: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

13

2000 Prentice Hall, Inc. All rights reserved.

lnmNoÏð ¹��B�Ï�ÀÜgr�vcu4¾yñËãò¹���s�uóÜYÍ�viÁQÁN��z�qcºÌ��qcu�y�/����z2q`ºÌÜÓz�åÌvP�#�4r�z5t�q

• Pseudocode - Top level: Shuffle and deal 52 cards

Initialize the suit array

Initialize the face array

Initialize the deck array

Shuffle the deck

Deal 52 cards

For each of the 52 cards

Place card number in randomlyselected unoccupied slot of deck

For each of the 52 cards

Find card number in deck arrayand print face and suit of card

Choose slot of deck randomly

While chosen slot of deck has beenpreviously chosen

Choose slot of deck randomlyPlace card number in chosen slot ofdeck

For each slot of the deck array

If slot contains card number Print the face and suit of thecard

Second refinement

Third refinement

First refinement

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

�C  ¬ ­ ¨ ®�¨ ¥F¤ ¨ ¯7¢sui t

¥ ­Nßf ace

¥j¦�¦#¥FÃZª�C  � ¬ ­ ¨ ®�¨ ¥j¤ ¨ ¯�¢

deck¥�¦5¦�¥jë  �ÆÇ¥j¤ ¤!È ¶ ­ £�®�¨ ² ­shuf f l e

«   �ÓÆÏ¥j¤ ¤!È ¶ ­ £�®�¨ ² ­deal

°  �¡1¢�È ¨ ­ ¢iÈ ¶ ­ £F®�¨ ² ­ ª

1 / * Fi g. 7. 24: f i g07_24. c

2 Car d shuf f l i ng deal i ng pr ogr am * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <st dl i b. h>

5 #i nc l ude <t i me. h>

6

7 voi d shuf f l e( i nt [ ] [ 13 ] ) ;

8 voi d deal ( const i nt [ ] [ 13 ] , const char * [ ] , const char * [ ] ) ;

9

10 i nt mai n( )

11 {

12 const char * sui t [ 4 ] =

13 { " Hear t s" , " Di amonds" , " Cl ubs" , " Spades" } ;

14 const char * f ace[ 13 ] =

15 { " Ace" , " Deuce" , " Thr ee" , " Four " ,

16 " Fi ve" , " Si x" , " Seven" , " Ei ght " ,

17 " Ni ne" , " Ten" , " Jack" , " Queen" , " Ki ng" } ;

18 i nt deck[ 4 ] [ 13 ] = { 0 } ;

19

20 s r and( t i me( 0 ) ) ;

21

22 shuf f l e( deck ) ;

23 deal ( deck , f ace, sui t ) ;

24

25 r et ur n 0;

26 }

27

28 voi d shuf f l e( i nt wDeck [ ] [ 13 ] )

29 {

30 i nt r ow, col umn, car d;

31

32 f or ( car d = 1; car d <= 52; car d++ ) {

Page 14: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

14

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

°  �¡1¢�È ¨ ­ ¢iÈ ¶ ­ £F®�¨ ² ­ ª

33 do {

34 r ow = r and( ) % 4;

35 col umn = r and( ) % 13;

36 } whi l e( wDeck[ r ow ] [ col umn ] ! = 0 ) ;

37

38 wDeck[ r ow ] [ col umn ] = car d;

39 }

40 }

41

42 voi d deal ( const i nt wDeck[ ] [ 13 ] , const char * wFace[ ] ,

43 const char * wSui t [ ] )

44 {

45 i nt car d, r ow, col umn;

46

47 f or ( car d = 1; car d <= 52; car d++ )

48

49 f or ( r ow = 0; r ow <= 3; r ow++ )

50

51 f or ( col umn = 0; col umn <= 12; col umn++ )

52

53 i f ( wDeck[ r ow ] [ col umn ] == car d )

54 pr i nt f ( " %5s of %- 8s%c" ,

55 wFace[ col umn ] , wSui t [ r ow ] ,

56 car d % 2 == 0 ? ’ \ n’ : ’ \ t ’ ) ;

57 }

The numbers 1-52 arerandomly placed into thedeck array.

Searches deck for thecar d number, then printsthe f ace and sui t .

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

±C¦5²�³�¦5¥�´�µ(¶N®�·j¶N® Si x of Cl ubs Seven of Di amonds Ace of Spades Ace of Di amonds Ace of Hear t s Queen of Di amondsQueen of Cl ubs Seven of Hear t s Ten of Hear t s Deuce of Cl ubs Ten of Spades Thr ee of Spades Ten of Di amonds Four of Spades Four of Di amonds Ten of Cl ubs Si x of Di amonds Si x of SpadesEi ght of Hear t s Thr ee of Di amonds Ni ne of Hear t s Thr ee of Hear t sDeuce of Spades Si x of Hear t s Fi ve of Cl ubs Ei ght of Cl ubsDeuce of Di amonds Ei ght of Spades Fi ve of Spades Ki ng of Cl ubs Ki ng of Di amonds Jack of SpadesDeuce of Hear t s Queen of Hear t s Ace of Cl ubs Ki ng of SpadesThr ee of Cl ubs Ki ng of Hear t s Ni ne of Cl ubs Ni ne of Spades Four of Hear t s Queen of SpadesEi ght of Di amonds Ni ne of Di amonds Jack of Di amonds Seven of Cl ubs Fi ve of Hear t s Fi ve of Di amonds Four of Cl ubs Jack of Hear t s Jack of Cl ubs Seven of Spades

Page 15: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

15

2000 Prentice Hall, Inc. All rights reserved.

lnmNono ~\t�z�qir!��s7�âr!tæ»(v�qcx/r�z�t�qi�

• Pointer to function– Contains address of function

– Similar to how array name is address of first element

– Function name is starting address of code that defines function

• Function pointers can be– Passed to functions

– Stored in arrays

– Assigned to other function pointers

2000 Prentice Hall, Inc. All rights reserved.

lnmZonoì~\t�z�qir!��s��âr!t�»(v�qcx/r�z5t�q`�ì�jp9p}�

• Example: bubblesort– Function bubbl e takes a function pointer

• bubbl e calls this helper function

• this determines ascending or descending sorting

– The argument in bubbl esor t for the function pointer:bool ( * compar e ) ( i nt , i nt )

tells bubbl esor t to expect a pointer to a function that takes two i nt sand returns a bool .

– If the parentheses were left out:bool * compar e( i nt , i nt )

• Declares a function that receives two integers and returns a pointer to abool

Page 16: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

16

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

�C  ¬ ­ ¨ ®�¨ ¥j¤ ¨ ¯�¢D¥j¦�¦#¥FÃô «  �±I¦5²F´i·j®�È ²�¦¥�ª2£�¢ ­Nß ¨ ­ ³c²F¦ß ¢Fª7£�¢ ­Nß ¨ ­ ³iª2²F¦5®�¨ ­ ³� «   �Ó±I¶N®�¥j·j·�¦5²F·�¦5¨ ¥j® ¢È ¶ ­ £�® ¨ ² ­ ·j²�¨ ­ ®�¢�¦N¨ ­ ® ²©�¶N©j©�¤ ¢�ª�²�¦�®� «   « ÆÏ¥j¤ ¤

bubbl e 

°  �±I¦5¨ ­ ®�¦5¢Fª7¶N¤ ®�ªU 

1 / * Fi g. 7. 26: f i g07_26. c

2 Mul t i pur pose sor t i ng pr ogr am usi ng f unct i on poi nt er s * /

3 #i nc l ude <st di o. h>

4 #def i ne SI ZE 10

5 voi d bubbl e( i nt [ ] , const i nt , i nt ( * ) ( i nt , i nt ) ) ;

6 i nt ascendi ng( i nt , i nt ) ;

7 i nt descendi ng( i nt , i nt ) ;

8

9 i nt mai n( )

10 {

11

12 i nt or der ,

13 count er ,

14 a[ SI ZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 } ;

15

16 pr i nt f ( " Ent er 1 t o sor t i n ascendi ng or der , \ n"

17 " Ent er 2 t o sor t i n descendi ng or der : " ) ;

18 scanf ( " %d" , &or der ) ;

19 pr i nt f ( " \ nDat a i t ems i n or i gi nal or der \ n" ) ;

20

21 f or ( count er = 0; count er < SI ZE; count er ++ )

22 pr i nt f ( " %5d" , a[ count er ] ) ;

23

24 i f ( or der == 1 ) {

25 bubbl e( a, SI ZE, ascendi ng ) ;

26 pr i nt f ( " \ nDat a i t ems i n ascendi ng or der \ n" ) ;

27 }

28 el se {

29 bubbl e( a, SI ZE, descendi ng ) ;

30 pr i nt f ( " \ nDat a i t ems i n descendi ng or der \ n" ) ;

31 }

32

Notice the functionpointer parameter.

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

°   �Ó¡0¢�È ¨ ­ ¢DÈ ¶ ­ £F®�¨ ² ­ ªU 

33 f or ( count er = 0; count er < SI ZE; count er ++ )

34 pr i nt f ( " %5d" , a[ count er ] ) ;

35

36 pr i nt f ( " \ n" ) ;

37

38 r et ur n 0;

39 }

40

41 voi d bubbl e( i nt wor k[ ] , const i nt s i ze,

42 i nt ( * compar e) ( i nt , i nt ) )

43 {

44 i nt pass, count ;

45

46 voi d swap( i nt * , i nt * ) ;

47

48 f or ( pass = 1; pass < s i ze; pass++ )

49

50 f or ( count = 0; count < s i ze - 1; count ++ )

51

52 i f ( ( * compar e) ( wor k[ count ] , wor k[ count + 1 ] ) )

53 swap( &wor k [ count ] , &wor k[ count + 1 ] ) ;

54 }

55

56 voi d swap( i nt * el ement 1Pt r , i nt * el ement 2Pt r )

57 {

58 i nt t emp;

59

60 t emp = * el ement 1Pt r ;

61 * el ement 1Pt r = * el ement 2Pt r ;

62 * el ement 2Pt r = t emp;

63 }

64

ascendi ng anddescendi ng return t r ue orf al se. bubbl e calls swap ifthe function call returns t r ue.

Notice how function pointersare called using thedereferencing operator. The *is not required, but emphasizesthat compar e is a functionpointer and not a function.

Page 17: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

17

2000 Prentice Hall, Inc. All rights reserved.

�H�6��� � ���

°   �Ó¡0¢�È ¨ ­ ¢DÈ ¶ ­ £F®�¨ ² ­ ªU 

±C¦5²�³�¦5¥�´�µ(¶N®�·j¶N®

65 i nt ascendi ng( i nt a, i nt b )

66 {

67 r et ur n b < a; / * swap i f b i s l ess t han a * /

68 }

69

70 i nt descendi ng( i nt a, i nt b )

71 {

72 r et ur n b > a; / * swap i f b i s gr eat er t han a * /

73 }

Ent er 1 t o sor t i n ascendi ng or der ,Ent er 2 t o sor t i n descendi ng or der : 1 Dat a i t ems i n or i gi nal or der 2 6 4 8 10 12 89 68 45 37Dat a i t ems i n ascendi ng or der 2 4 6 8 10 12 37 45 68 89

Ent er 1 t o sor t i n ascendi ng or der ,Ent er 2 t o sor t i n descendi ng or der : 2 Dat a i t ems i n or i gi nal or der 2 6 4 8 10 12 89 68 45 37Dat a i t ems i n descendi ng or der 89 68 45 37 12 10 8 6 4 2

2000 Prentice Hall, Inc. All rights reserved.

Chapter 8Characters and Strings

��������� �d� �� ������� ����������� ���d� � AU�6�I��&�bn"$�I�)&�, 3'�1JFXZ���a� ��@�3'&+����>nO�&�� &����5"�� 3d� : >õO�&+� &-�1�#"$�6ö6&+�C�+, � ��@4÷Q� *�� &�� Ed� = X��2�a� �I@[>\����ø�"�� 3N� �$�nAU�6������� ����3d� K X��#&+���-&+� �4�5�6<����#ù!;P�I�7<-���-÷9� *�� &(� EHAU�j���1�7� �$�I3d� V X��2�a� �I@BúD&+�6� <-�6, &���� �'�hAU�6���0�7� ����3gû5XZ�7�#� �I@Böj&(���+, � ��@4÷9� *�� &(� Ejüd� �� >?��b[<F&(�)� 3Q�$�TAC�6���0�7� ����3Ç��J��2O�"PX��2�a� �I@Bö6&����(, � ��@4÷Q� *-� &+� Ed� d X�"�&(� �$OTAC�6�C���7� ����3Ç��J��2O�"PX��2�a� ��@Bö6&����(, � ��@4÷Q� *-� &+� Ed� k úD"�bc�$� E[AU�6������� �$��3$��JM�7O�"YXZ�7�)� ��@4öj&(���+, � ��@4÷9� *�� &(� Ed� ��2ý ;i�2O�"$�6AU�6�I���2� ����3Ç��J��2O�"ÓXZ�2�)� ��@Böj&(���(, � ��@4÷9� *�� &+� E

Page 18: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

18

2000 Prentice Hall, Inc. All rights reserved.

çHmZo pQqcrMs�t/uwvixyr�z5t{q

• Introduce some standard libraryfunctions– Easy string and character processing

– Programs can process characters, strings, linesof text, and blocks of memory

• These techniques used to make– Word processors

– Page layout software

– Typesetting programs

2000 Prentice Hall, Inc. All rights reserved.

çHm�| »(v�qcuB��å���qcr!���5�ât/ÁTÜgr�sCz2qiº4�â�wqcu¹þÍc�ws��Bxér!��s��

• Characters– Building blocks of programs

• Every program is a sequence ofmeaningfully grouped characters

– Character constant - an i nt valuerepresented as a character in single quotes• ’ z ’ represents the integer value of z

Page 19: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

19

2000 Prentice Hall, Inc. All rights reserved.

çHm�| »(v�qcuB��å���qcr!���5�ât/ÁTÜgr�sCz2qiº4�â�wqcu¹þÍc�ws��Bx/r!�{s����6p�p��

• Strings– Series of characters treated as a single unit

• Can include letters, digits, and certain specialcharacters (* , / , $)

– String literal (string constant) - written indouble quotes• " Hel l o"

– Strings are arrays of characters• String a pointer to first character

• Value of string is the address of firstcharacter

2000 Prentice Hall, Inc. All rights reserved.

çHm�| »(v�qcuB��å���qcr!���5�ât/ÁTÜgr�sCz2qiº4�â�wqcu¹þÍc�ws��Bxér!��s����6p�p9p}�

• String declarations– Declare as a character array or a variable

of type char *

char col or [ ] = " bl ue" ;

char * col or Pt r = " bl ue" ;

– Remember that strings represented ascharacter arrays end with ’ \ 0’

• col or has 5 elements

Page 20: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

20

2000 Prentice Hall, Inc. All rights reserved.

ÿ���� �������� ���������������������! "�$#%���&�')(���*�%+������,�.-0/2143

• Inputting strings– Use scanf

scanf ( " %s" , wor d) ;

• Copies input into wor d[ ] , which does notneed & (because a string is a pointer)

– Remember to leave space for ’ \ 0’

2000 Prentice Hall, Inc. All rights reserved.

ÿ���5 '6(�&�7�8+����9��:��&���; <�#>=? <@��,�&�,A

• Character Handling Library– Includes functions to perform useful tests

and manipulations of character data– Each function receives a character (an i nt )

or EOF as an argument

Page 21: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

21

2000 Prentice Hall, Inc. All rights reserved.

ÿ���56'6(�&�7��+B���9��:��&���; <�#>=? <@��,�&�7AC-D/E/F3

• In <ct ype. h>Prototype Description

i nt i sdi gi t ( i nt c ) Returns t r ue if c is a digit and f al se otherwise.

i nt i sal pha( i nt c ) Returns t r ue if c is a letter and f al se otherwise.

i nt i sal num( i nt c ) Returns t r ue if c is a digit or a letter and f al se otherwise.

i nt i sxdi gi t ( i nt c ) Returns t r ue if c is a hexadecimal digit character and f al se otherwise.

i nt i s l ower ( i nt c ) Returns t r ue if c is a lowercase letter and f al se otherwise.

i nt i supper ( i nt c ) Returns t r ue if c is an uppercase letter; f al se otherwise.

i nt t ol ower ( i nt c ) If c is an uppercase letter, t ol ower returns c as a lowercase letter. Otherwise, t ol ower returns the argument unchanged.

i nt t oupper ( i nt c ) If c is a lowercase letter, t oupper returns c as an uppercase letter. Otherwise, t oupper returns the argument unchanged.

i nt i sspace( i nt c ) Returns t r ue if c is a white-space character—newline (’ \ n’ ), space (’ ’ ), form feed (’ \ f ’ ), carriage return (’ \ r ’ ), horizontal tab (’ \ t ’ ), or vertical tab (’ \ v ’ )—and f al se otherwise

i nt i scnt r l ( i nt c ) Returns t r ue if c is a control character and f al se otherwise.

i nt i spunct ( i nt c ) Returns t r ue if c is a printing character other than a space, a digit, or a letter and f al se otherwise.

i nt i spr i nt ( i nt c ) Returns t r ue value if c is a printing character including space (’ ’ ) and f al se otherwise.

i nt i sgr aph( i nt c ) Returns t r ue if c is a printing character other than space (’ ’ ) and f al se otherwise.

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQTS!UWV�X8Y[Z\V]X�ZW^

_ QT`aZW^cb7U\^Fdfe*Zhgie2g

j QT`a^Fkclme

1 / * Fi g. 8. 2: f i g08_02. c

2 Usi ng f unc t i ons i sdi gi t , i sal pha, i sal num, and i sxdi gi t * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <ct ype. h>

5

6 i nt mai n( )

7 {

8 pr i nt f ( " %s\ n%s%s\ n%s%s\ n\ n" , " Accor di ng t o i sdi gi t : " ,

9 i sdi gi t ( ’ 8’ ) ? " 8 i s a " : " 8 i s not a " , " di gi t " ,

10 i sdi gi t ( ’ #’ ) ? " # i s a " :

11 " # i s not a " , " di gi t " ) ;

12 pr i nt f ( " %s\ n%s%s\ n%s%s\ n%s%s\ n%s%s\ n\ n" ,

13 " Accor di ng t o i sal pha: " ,

14 i sal pha( ’ A’ ) ? " A i s a " : " A i s not a " , " l et t er " ,

15 i sal pha( ’ b’ ) ? " b i s a " : " b i s not a " , " l et t er " ,

16 i sal pha( ’ &’ ) ? " & i s a " : " & i s not a " , " l et t er " ,

17 i sal pha( ’ 4’ ) ? " 4 i s a " :

18 " 4 i s not a " , " l et t er " ) ;

19 pr i nt f ( " %s\ n%s%s\ n%s%s\ n%s%s\ n\ n" ,

20 " Accor di ng t o i sal num: " ,

21 i sal num( ’ A’ ) ? " A i s a " : " A i s not a " ,

22 " di gi t or a l et t er " ,

23 i sal num( ’ 8’ ) ? " 8 i s a " : " 8 i s not a " ,

24 " di gi t or a l et t er " ,

25 i sal num( ’ #’ ) ? " # i s a " : " # i s not a " ,

26 " di gi t or a l et t er " ) ;

27 pr i nt f ( " %s\ n%s%s\ n%s%s\ n%s%s\ n%s%s\ n%s%s\ n" ,

28 " Accor di ng t o i sxdi gi t : " ,

29 i sxdi gi t ( ’ F’ ) ? " F i s a " : " F i s not a " ,

30 " hexadeci mal di gi t " ,

31 i sxdi gi t ( ’ J ’ ) ? " J i s a " : " J i s not a " ,

32 " hexadeci mal di gi t " ,

Page 22: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

22

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

`T^FUon]^FV�dqp�rme*s]rme

33 i sxdi gi t ( ’ 7’ ) ? " 7 i s a " : " 7 i s not a " ,

34 " hexadeci mal di gi t " ,

35 i sxdi gi t ( ’ $’ ) ? " $ i s a " : " $ i s not a " ,

36 " hexadeci mal di gi t " ,

37 i sxdi gi t ( ’ f ’ ) ? " f i s a " : " f i s not a " ,

38 " hexadeci mal di gi t " ) ;

39 r et ur n 0;

40 }

Accor di ng t o i sdi gi t :8 i s a di gi t# i s not a di gi t

Accor di ng t o i sal pha:A i s a l et t erb i s a l et t er& i s not a l et t er4 i s not a l et t er

Accor di ng t o i sal num:A i s a di gi t or a l et t er8 i s a di gi t or a l et t er# i s not a di gi t or a l et t er

Accor di ng t o i sxdi gi t :F i s a hexadeci mal di gi tJ i s not a hexadeci mal di gi t7 i s a hexadeci mal di gi t$ i s not a hexadeci mal di gi tf i s a hexadeci mal di gi t

2000 Prentice Hall, Inc. All rights reserved.

ÿ���t6�����u <�#v'w�9�xy���*�z {���|�����$+B�� �����

• Conversion functions– In <st dl i b. h> (general utilities library)

– Convert strings of digits to integer and floating-point values

Prototype Description

doubl e at of ( cons t c har * nPt r ) Converts the string nPt r to doubl e .

i nt at oi ( cons t char * nPt r ) Converts the string nPt r to i nt .

l ong at ol ( c ons t c har * nPt r ) Converts the string nPt r to long i nt .

doubl e s t r t od( cons t char * nPt r , c har * * endPt r )

Converts the string nPt r to doubl e.

l ong s t r t ol ( cons t c har * nPt r , char * * endPt r , i nt base )

Converts the string nPt r to l ong.

uns i gned l ong s t r t oul ( cons t char * nPt r , c har * * endPt r , i nt base )

Converts the string nPt r to uns i gned l ong .

Page 23: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

23

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQT}~l[k e*kcV]�ck �0Z� V]^�k V��]�cZ

_ QT�yU\l � Z\^ce�g�e*^<kcl[n_ Q7Pz��g!gmkcn]l�e*U� V]^�k V��]�cZ

j QT`a^Fkclme

`T^FUon]^FV�dqp�rme*s]rme

1 / * Fi g. 8. 6: f i g08_06. c

2 Usi ng at of * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <st dl i b. h>

5

6 i nt mai n( )

7 {

8 doubl e d;

9

10 d = at of ( " 99. 0" ) ;

11 pr i nt f ( " %s%. 3f \ n%s%. 3f \ n" ,

12 " The st r i ng \ " 99. 0\ " conver t ed t o doubl e i s " , d,

13 " The conver t ed val ue di v i ded by 2 i s " ,

14 d / 2. 0 ) ;

15 r et ur n 0;

16 }

The st r i ng " 99. 0" conver t ed t o doubl e i s 99. 000The conver t ed val ue di v i ded by 2 i s 49. 500

2000 Prentice Hall, Inc. All rights reserved.

ÿ���� �����������*>/���������\���$���%��B=O "@%�,���*A�����+��� �����

• Functions in <st di o. h>– Used to manipulate character and string data�,�u������� �����m� ���������K��� �,���i����� �������� 2��� � �m��� ���

i n t g e t c h a r ( v o i d ) ; I nputs the nex t character f rom the standard i nput and returns i t as an i nteger.

c h a r * g e t s ( c h a r * s ) ; I nputs characters f rom the standard i nput i nto the array s unti l a new l i ne or end-of -f i le character i s encountered. A term inati ng nul l character i s appended to the array .

i n t p u t c h a r ( i n t c ) ; Pri nts the character stored in c .

i n t p u t s ( c o n s t c h a r * s ) ; Pri nts the str i ng s f ol l ow ed by a new l ine character.

i n t s p r i n t f ( c h a r * s , c o n s t c h a r * f o r ma t , . . . ) ;

Equiv alent to p r i n t f , except the output i s stored in the array s i nstead of printing i t on the screen.

i n t s s c a n f ( c h a r * s , c o n s t c h a r * f o r ma t , . . . ) ;

Equiv alent to s c a n f , except the i nput i s read f rom the array s i nstead of reading i t f rom the k ey board.

Page 24: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

24

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQT}~l[k e*kcV]�ck �0Z� V]^�k V��]�cZTg

_ QT}~l[s]rme

j QT`a^Fkclme

j Q7P¢¡Rr[l[£he*kcU\lX]Zhb,kcl[k e*kcUWl�¤,l[Uae*Z^�Z\£Wr[^ gDkcUWl[¥

1 / * Fi g. 8. 13: f i g08_13. c

2 Usi ng get s and put char * /

3 #i nc l ude <st di o. h>

4

5 i nt mai n( )

6 {

7 char sent ence[ 80 ] ;

8 voi d r ever se( const char * const ) ;

9

10 pr i nt f ( " Ent er a l i ne of t ext : \ n" ) ;

11 get s( sent ence ) ;

12

13 pr i nt f ( " \ nThe l i ne pr i nt ed backwar ds i s : \ n" ) ;

14 r ever se( sent ence ) ;

15

16 r et ur n 0;

17 }

18

19 voi d r ever se( cons t char * const sPt r )

20 {

21 i f ( sPt r [ 0 ] == ’ \ 0’ )

22 r et ur n;

23 el se {

24 r ever se( &sPt r [ 1 ] ) ;

25 put char ( sPt r [ 0 ] ) ;

26 }

27 }

Ent er a l i ne of t ext :Char act er s and St r i ngs

The l i ne pr i nt ed backwar ds i s:sgni r t S dna s r et car ahC

r ever se calls itself using substrings ofthe original string. When it reaches the’ \ 0’ character it prints using put char

2000 Prentice Hall, Inc. All rights reserved.

ÿ���¦ �����u <�#>§)�&�� <���������� ����������+��� ����$��������(������u <�#>:¨���&�< ;�#>=O ;@%�*���,A

• Defined in <st r i ng. h>• String handling library has functions to

– Manipulate string data– Search strings– Tokenize strings– Determine string length

©«ª,¬7­E® ¯ °E¬0±E² °E® °E® ³<±K´ ©2ª*¬7­�® ¯ °�¬Dµ�´E¶ ­E² ¯ ±K® ¯ °E¬char * st r cpy( char * s1, const char * s2 )

Copies string s2 into array s1. The value of s1 is returned.

char * st r ncpy( char * s1, const char * s2, s i ze_t n )

Copies at most n characters of string s2 into array s1. The value of s1 is returned.

char * st r cat ( char * s1, const char * s2 )

Appends string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.

char * st r ncat ( char * s1, const char * s2, s i ze_t n )

Appends at most n characters of string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.

Page 25: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

25

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQT}~l[k e*kcV]�ck �0Z� V]^�k V��]�cZTg

_ QT¡Rr[l[£Te*kcU\l¨£\V�� � g

j QT`a^Fkclme

`T^FUon]^FV�dqp�rme*s]rme

1 / * Fi g. 8. 19: f i g08_19. c

2 Usi ng st r cat and st r ncat * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <st r i ng. h>

5

6 i nt mai n( )

7 {

8 char s1[ 20 ] = " Happy " ;

9 char s2[ ] = " New Year " ;

10 char s3[ 40 ] = " " ;

11

12 pr i nt f ( " s1 = %s\ ns2 = %s\ n" , s1, s2 ) ;

13 pr i nt f ( " s t r cat ( s1, s2 ) = %s\ n" , st r cat ( s1, s2 ) ) ;

14 pr i nt f ( " s t r ncat ( s3, s1, 6 ) = %s\ n" , s t r ncat ( s3, s1, 6 ) ) ;

15 pr i nt f ( " s t r cat ( s3, s1 ) = %s\ n" , st r cat ( s3, s1 ) ) ;

16 r et ur n 0;

17 }

s1 = Happys2 = New Yearst r cat ( s1, s2 ) = Happy New Yearst r ncat ( s3, s1, 6 ) = Happyst r cat ( s3, s1 ) = Happy Happy New Year

2000 Prentice Hall, Inc. All rights reserved.

ÿ��E· '.�� v�����! ��?���������+��� ����$��������(�C�����i ;�#:¨���&�< ;�#>=? ;@%�,���*A

• Comparing strings– Computer compares numeric ASCII codes of

characters in string

– Appendix D has a list of character codes

• i nt st r cmp( const char * s1, constchar * s2 ) ;

– Compares string s1 to s2

– Returns a negative number (s1 < s2), zero (s1== s2), or a positive number (s1 > s2)

• i nt st r ncmp( const char * s1, const

Page 26: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

26

2000 Prentice Hall, Inc. All rights reserved.

ÿ��}ÿ ���B���,+�(|�����$+B�� �������B�¸�R(�¹�����! ;�#>:¨���&�< ;�#=? ;@%�,���*A

º,»u¼u½�¾�¿ À�¼ÂÁmà À�¾�À�¾�ÄKÁDÅ º*»u¼u½�¾�¿ À�¼ÂÆDÅ�Ç2½�à ¿ Á�¾{¿ À�¼char * st r chr ( const char * s, i nt c ) ;

Locates the first occurrence of character c in string s . If c is found, a pointer to c in s is returned. Otherwise, a NULL pointer is returned.

si ze_t s t r cspn( const char * s1, const char * s2 ) ;

Determines and returns the length of the initial segment of string s1 consisting of characters not contained in string s2.

si ze_t s t r spn( const char * s1, const char * s2 ) ;

Determines and returns the length of the initial segment of string s1 consisting only of characters contained in string s2.

char * st r pbr k( const char * s1, const char * s2 ) ;

Locates the first occurrence in string s1 of any character in string s2. If a character from string s2 is found, a pointer to the character in string s1 is returned. Other-wise, a NULL pointer is returned.

char * st r r chr ( const char * s, i nt c ) ;

Locates the last occurrence of c in string s . If c is found, a pointer to c in string s is returned. Otherwise, a NULL pointer is returned.

char * st r s t r ( const char * s1, const char * s2 ) ;

Locates the first occurrence in string s1 of string s2. If the string is found, a pointer to the string in s1 is returned. Otherwise, a NULL pointer is returned.

char * st r t ok( char * s1, const char * s2 ) ;

A sequence of calls to st r t ok breaks string s1 into “ tokens”—logical pieces such as words in a line of text—separated by characters contained in string s2. The first call contains s1 as the first argument, and subsequent calls to continue tokenizing the same string contain NULL as the first argument. A pointer to the current token is returned by each call. If there are no more tokens when the function is called, NULL is returned.

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQT}~l[k e*kcV]�ck �0Z� V]^�k V��]�cZTg

_ QT¡Rr[l[£Te*kcU\l¨£\V�� � g

j QT`a^Fkclme

`T^FUon]^FV�dqp�rme*s]rme

1 / * Fi g. 8. 27: f i g08_27. c

2 Usi ng st r spn * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <st r i ng. h>

5

6 i nt mai n( )

7 {

8 const char * st r i ng1 = " The val ue i s 3. 14159" ;

9 const char * st r i ng2 = " aehi l sTuv" ;

10

11 pr i nt f ( " %s%s\ n%s%s\ n\ n%s\ n%s%u\ n" ,

12 " s t r i ng1 = " , st r i ng1, " st r i ng2 = " , st r i ng2,

13 " The l engt h of t he i ni t i al segment of st r i ng1" ,

14 " cont ai ni ng onl y char act er s f r om st r i ng2 = " ,

15 st r spn( st r i ng1, st r i ng2 ) ) ;

16 r et ur n 0;

17 }

st r i ng1 = The val ue i s 3. 14159st r i ng2 = aehi l sTuv

The l engt h of t he i ni t i al segment of st r i ng1cont ai ni ng onl y char ac t er s f r om st r i ng2 = 13

Page 27: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

27

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQT}~l[k e*kcV]�ck �0Z� V]^�k V��]�cZTg

_ QT¡Rr[l[£Te*kcU\l¨£\V�� � g

j QT`a^Fkclme

`T^FUon]^FV�dqp�rme*s]rme

1 / * Fi g. 8. 29: f i g08_29. c2 Usi ng st r t ok * /3 #i nc l ude <st di o. h>

4 #i nc l ude <st r i ng. h>56 i nt mai n( )7 {

8 char s t r i ng[ ] = " Thi s i s a sent ence wi t h 7 t okens" ;9 char * t okenPt r ;

1011 pr i nt f ( " %s\ n%s\ n\ n%s\ n" ,12 " The st r i ng t o be t okeni zed i s: " , st r i ng,

13 " The t okens ar e: " ) ;1415 t okenPt r = st r t ok( s t r i ng, " " ) ;1617 whi l e ( t okenPt r ! = NULL ) {

18 pr i nt f ( " %s\ n" , t okenPt r ) ;19 t okenPt r = s t r t ok ( NULL, " " ) ;20 }21

22 r et ur n 0;23 }

The st r i ng t o be t okeni zed i s:Thi s i s a sent ence wi t h 7 t okens

The t okens ar e:Thi si sasent encewi t h7t okens

2000 Prentice Hall, Inc. All rights reserved.

ÿ��FÈ�§)�� ����7AC�����+��� ����$���É�¸��(�Ê�����u <�#&Ë(���&�< ;�#>=O ;@%�*���,A

• Memory Functions– Manipulate, compare, and search blocks of

memory

– Can manipulate any block of data

• Pointer parameters are voi d *– Any pointer can be assigned to voi d * , and

vice versa– voi d * cannot be dereferenced

• Each function receives a size argument specifyingthe number of bytes (characters) to process

Page 28: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

28

2000 Prentice Hall, Inc. All rights reserved.

ÿ��FÈ�§)�� ����7AC�����+��� ����$���É�¸��(�Ê�����u <�#&Ë(�&���; <�#>=O ;@%�*���,AC-D/�/�3

Prototype Description

voi d * memcpy( voi d * s1, const voi d * s2, s i ze_t n )

Copies n characters from the object pointed to by s2 into the object pointed to by s1. A pointer to the resulting object is returned.

voi d * memmove( voi d * s1, const voi d * s2, s i ze_t n )

Copies n characters from the object pointed to by s2 into the object pointed to by s1. The copy is performed as if the characters are first copied from the object pointed to by s2 into a temporary array, and then copied from the temporary array into the object pointed to by s1. A pointer to the resulting object is returned.

i nt memcmp( const voi d * s1, const voi d * s2, s i ze_t n )

Compares the first n characters of the objects pointed to by s1 and s2. The function returns 0, less than 0, or greater than 0 if s1 is equal to, less than or greater than s2, respectively.

voi d * memchr ( const voi d * s, i nt c, s i ze_t n )

Locates the first occurrence of c (converted to uns i gned char ) in the first n characters of the object pointed to by s . If c is found, a pointer to c in the object is returned. Otherwise, 0 is returned.

voi d * memset ( voi d * s , i nt c, s i ze_t n ) Copies c (converted to unsi gned char ) into the first n characters of the object pointed to by s . A pointer to the result is returned.

"Object" refers to a block of data

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQT}~l[k e*kcV]�ck �0Z� V]^�k V��]�cZTg

_ QT¡Rr[l[£Te*kcU\l¨£\V�� � g

j QT`a^Fkclme

`T^FUon]^FV�dqp�rme*s]rme

1 / * Fi g. 8. 32: f i g08_32. c

2 Usi ng memmove * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <st r i ng. h>

5

6 i nt mai n( )

7 {

8 char x [ ] = " Home Sweet Home" ;

9

10 pr i nt f ( " %s%s\ n" ,

11 " The st r i ng i n ar r ay x bef or e memmove i s: " , x ) ;

12 pr i nt f ( " %s%s\ n" ,

13 " The st r i ng i n ar r ay x af t er memmove i s: " ,

14 memmove( x, &x[ 5 ] , 10 ) ) ;

15

16 r et ur n 0;

17 }

The st r i ng i n ar r ay x bef or e memmove i s: Home Sweet HomeThe st r i ng i n ar r ay x af t er memmove i s: Sweet Home Home

Page 29: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

29

2000 Prentice Hall, Inc. All rights reserved.

ÿ���Ì?Í �6��(�����z�Î�+B�� �����&�B�y��(�Ê�����i <�#>:¨���&�< ;�#=? ;@%�,���*A

• char * st r er r or ( i nt er r or num ) ;

– Creates a system-dependent error messagebased on er r or num

– Returns a pointer to the string

• si ze_t s t r l en( const char * s ) ;

– Returns the number of characters (before NULL)in string s

2000 Prentice Hall, Inc. All rights reserved.

G�H0IKJ L MON

PRQ�¡Rr[l[£Te*kcUWl�£\V]�c�

_ QT`a^Fkclme

`T^FUon]^FV�dqp�rme*s]rme

1 / * Fi g. 8. 37: f i g08_37. c

2 Usi ng st r er r or * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <st r i ng. h>

5

6 i nt mai n( )

7 {

8 pr i nt f ( " %s\ n" , st r er r or ( 2 ) ) ;

9 r et ur n 0;

10 }

No such f i l e or di r ect or y

Page 30: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

30

2000 Prentice Hall, Inc. All rights reserved.

Chapter 10 - Structures, Unions, BitFields, and Enumerations

p�rme*�ck l[ZÏ;Ð�Ñ;Ï Ò�ÓuÔ;Õ Ö�×]ØuÙ�Ô;Ú Ö]ÓÏ;Ð�Ñ Û ÜuÔ"Õ«ØuÙaÔ"Ø0Õ ÝßÞTÝTà<Ú ÓDÚ Ô;Ú ÖoÓuáÏ;Ð�Ñ â Ò�Ó0Ú Ô"Ú ãÂä Ú å�Ú Óuæ�Ü�Ô7Õ{ØuÙ�Ô"ØDÕ Ý�áÏ;Ð�Ñ ç è�ÙaÙ�ÝTáEáRÚ Óuæ%éêÝoë�ìmÝ]Õ áWÖ�à�Ü�Ô"Õ~ØuÙ�Ô;Ø0Õ Ý�áÏ;Ð�Ñ í î�áRÚ Óuæ�Ü�Ô"Õ~ØuÙ�Ô7ØmÕ Ý�áoï¸Ú Ô"ð�ñ�Ø0ÓiÙaÔ7Ú ÖoÓuáÏ;Ð�Ñ ò ó,ôOõ�Ý�×[Ý�àÏ;Ð�Ñ ö îaÓ0Ú ÖoÓuáÏ;Ð�Ñ;Ï�Ï ÷uÓ0Ø0ëÝ]Õ ãøÔ"Ú ÖoÓúùûÖ]Óiá�Ô~ã�ÓuÔ�áÏ;Ð�Ñ ü ýmÚ Ô�ï¸Ú áEÝÎþ�õmÝ\Õ ã[Ô{ÖoÕ áÏ;Ð�Ñ;Ï;Ð ýmÚ Ô[ñ�Ú Ý]ä ×[á

2000 Prentice Hall, Inc. All rights reserved.

Ì?Í���Ì /�����*��&�$+B�� ��9�

• Structures– Collections of related variables

(aggregates) under one name• Can contain variables of different data types

– Commonly used to define records to bestored in files

– Combined with pointers, can createlinked lists, stacks, queues, and trees

Page 31: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

31

2000 Prentice Hall, Inc. All rights reserved.

Ì?Í��F� �����i�+B�R���*� ÿß���� ;�� ��� ����$�

• Examplest r uct car d {

char * f ace;

char * sui t ; } ;

– st r uct introduces the definition for structurecar d

– car d is the structure name and is used todeclare variables of the structure type

– car d contains two members of type char *- f ace and sui t

2000 Prentice Hall, Inc. All rights reserved.

������� ���� ���� ������������������� �!�#"%$'&(&�)

• Struct information– A struct cannot contain an instance of itself– Can contain a member that is a pointer to the same

structure type– Structure definition does not reserve space in memory– Creates a new data type that is used to declare structure

variables.

• Declarations– Declared like other variables:

car d oneCar d, deck[ 52 ] , * cPt r ;

– Can use a comma separated list:st r uct car d { char * f ace; char * sui t ;} oneCar d, deck[ 52 ] , * cPt r ;

Page 32: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

32

2000 Prentice Hall, Inc. All rights reserved.

�������*���� ���� ��+�����������,�-��-�.��"/$'&0&(&�)

• Valid Operations– Assigning a structure to a structure of the same

type– Taking the address (&) of a structure

– Accessing the members of a structure– Using the si zeof operator to determine the

size of a structure

2000 Prentice Hall, Inc. All rights reserved.

������12&0��� ���354���6����78�9��: ���� ��;��"

• Initializer lists– Example:

car d oneCar d = { " Thr ee" ," Hear t s" } ;

• Assignment statements– Example:

car d t hr eeHear t s = oneCar d;– Or:

car d t hr eeHear t s;

t hr eeHear t s. f ace = “ Thr ee” ;

t hr eeHear t s. sui t = “ Hear t s” ;

Page 33: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

33

2000 Prentice Hall, Inc. All rights reserved.

�����=< >?������"@"A����7CB*�EDGF��!�+"H���I���J #��� ��+��"

• Accessing structure members– Dot operator (. ) - use with structure variable name

car d myCar d;

pr i nt f ( " %s" , myCar d. sui t ) ;

– Arrow operator (- >) - use with pointers to structurevariables

car d * myCar dPt r = &myCar d;

pr i nt f ( " %s" , myCar dPt r - >sui t ) ;

myCar dPt r - >sui t equivalent to ( * myCar dPt r) . sui t

2000 Prentice Hall, Inc. All rights reserved.

������K2LM"N�O��7G���J #��� P�;��"HQR� �SUTV ��#������.��"

• Passing structures to functions– Pass entire structure

• Or, pass individual members

– Both pass call by value

• To pass structures call-by-reference– Pass its address

– Pass reference to it

• To pass arrays call-by-value– Create a structure with the array as a member

– Pass the structure

Page 34: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

34

2000 Prentice Hall, Inc. All rights reserved.

�����=W XZY�[���\]�^�

• t ypedef– Creates synonyms (aliases) for previously

defined data types– Use t ypedef to create shorter type names.

– Example: t ypedef Car d * Car dPt r ;

– Defines a new type name Car dPt r as asynonym for type Car d *

– t ypedef does not create a new data type

• Only creates an alias

2000 Prentice Hall, Inc. All rights reserved.

�����(_ `bac35DG[d4��!eIfg��75S�hjiA�E���(�!�:DU35�����lk/35�;\5h"AS, ��(�m4��O��7G3n��\o�p��354��O��7G�q��DG �4�3d����!�

• Pseudocode:– Create an array of car d structures

– Put cards in the deck

– Shuffle the deck

– Deal the cards

Page 35: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

35

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z{m|~}:���V�����b���V�����

{m|+{����~��� ���st r uct

{m|����m�������;���b�� ���~�;����� � �~�

{m| �]�-��� �;������� ���deck[ ]�����

f ace[ ]

{m|  ]�-��� �;������� ���sui t [ ]

1 / * Fi g. 10. 3: f i g10_03. c

2 The car d shuf f l i ng and deal i ng pr ogr am usi ng st r uct ur es * /

3 #i nc l ude <st di o. h>

4 #i nc l ude <st dl i b. h>

5 #i nc l ude <t i me. h>

6

7 st r uct car d {

8 const char * f ace;

9 const char * sui t ;

10 } ;

11

12 t ypedef s t r uc t car d Car d;

13

14 voi d f i l l Deck( Car d * const , cons t char * [ ] ,

15 const char * [ ] ) ;

16 voi d shuf f l e( Car d * const ) ;

17 voi d deal ( const Car d * cons t ) ;

18

19 i nt mai n( )

20 {

21 Car d deck[ 52 ] ;

22 const char * f ace[ ] = { " Ace" , " Deuce" , " Thr ee" ,

23 " Four " , " Fi ve" ,

24 " Si x" , " Seven" , " Ei ght " ,

25 " Ni ne" , " Ten" ,

26 " Jack" , " Queen" , " Ki ng" } ;

27 const char * sui t [ ] = { " Hear t s " , " Di amonds" ,

28 " Cl ubs" , " Spades" } ;

29

30 s r and( t i me( NULL ) ) ;

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

�~|~¡Z�����V�b¢]� �u�

�~|f i l l Deck

�~|+{shuf f l e

�~|��deal

�b|~�m�����~�;���b������������ �;�����£�

31

32 f i l l Deck( deck, f ace, sui t ) ;

33 shuf f l e( deck ) ;

34 deal ( deck ) ;

35 r et ur n 0;

36 }

37

38 voi d f i l l Deck( Car d * const wDeck, const char * wFace[ ] ,

39 const char * wSui t [ ] )

40 {

41 i nt i ;

42

43 f or ( i = 0; i <= 51; i ++ ) {

44 wDeck[ i ] . f ace = wFace[ i % 13 ] ;

45 wDeck[ i ] . sui t = wSui t [ i / 13 ] ;

46 }

47 }

48

49 voi d shuf f l e( Car d * const wDeck )

50 {

51 i nt i , j ;

52 Car d t emp;

53

54 f or ( i = 0; i <= 51; i ++ ) {

55 j = r and( ) % 52;

56 t emp = wDeck[ i ] ;

57 wDeck[ i ] = wDeck[ j ] ;

58 wDeck[ j ] = t emp;

59 }

60 }

Put all 52 cards in the deck.f ace and sui t determined byremainder (modulus).

Select random number between 0 and 51.Swap element i with that element.

Page 36: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

36

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

�b|~�m�����~�;���b������������ �;�����£�

61

62 voi d deal ( const Car d * cons t wDeck )

63 {

64 i nt i ;

65

66 f or ( i = 0; i <= 51; i ++ )

67 pr i nt f ( " %5s of %- 8s%c" , wDeck[ i ] . f ace,

68 wDeck[ i ] . sui t ,

69 ( i + 1 ) % 2 ? ’ \ t ’ : ’ \ n’ ) ;

70 }

Cycle through array and printout data.

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

¤~�=�¦¥��=�V¢¨§��£� � �£�

Ei ght of Di amonds Ace of Hear t sEi ght of Cl ubs Fi ve of SpadesSeven of Hear t s Deuce of Di amonds Ace of Cl ubs Ten of Di amondsDeuce of Spades Si x of Di amondsSeven of Spades Deuce of Cl ubs Jack of Cl ubs Ten of Spades Ki ng of Hear t s Jack of Di amondsThr ee of Hear t s Thr ee of Di amondsThr ee of Cl ubs Ni ne of Cl ubs Ten of Hear t s Deuce of Hear t s Ten of Cl ubs Seven of Di amonds Si x of Cl ubs Queen of Spades Si x of Hear t s Thr ee of Spades Ni ne of Di amonds Ace of Di amonds Jack of Spades Fi ve of Cl ubs Ki ng of Di amonds Seven of Cl ubs Ni ne of Spades Four of Hear t s Si x of Spades Ei ght of SpadesQueen of Di amonds Fi ve of Di amonds Ace of Spades Ni ne of Hear t s Ki ng of Cl ubs Fi ve of Hear t s Ki ng of Spades Four of Di amondsQueen of Hear t s Ei ght of Hear t s Four of Spades Jack of Hear t s Four of Cl ubs Queen of Cl ubs

Page 37: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

37

2000 Prentice Hall, Inc. All rights reserved.

�����=© L^�����!��"

• uni on– Memory that contains a variety of objects over

time

– Only contains one data member at a time

– Members of a union share space

– Conserves storage

– Only the last data member defined can beaccessed

• uni on declarations– Same as st r uct

uni on Number {

2000 Prentice Hall, Inc. All rights reserved.

�����=© L������!�#"%$£&0&�)

• Valid uni on operations– Assignment to union of same type: =

– Taking address: &

– Accessing union members: .

– Accessing members using pointers: - >

Page 38: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

38

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

{m|~�A�~�+� ���]���������

{m|+{��-��� �;������� ���ª ����� �V«����~�

�~|m¬��~� ª �V�=����«����~�

�b|~¤­�=���£�

1 / * Fi g. 10. 5: f i g10_05. c

2 An exampl e of a uni on * /

3 #i nc l ude <st di o. h>

4

5 uni on number {

6 i nt x;

7 doubl e y;

8 } ;

9

10 i nt mai n( )

11 {

12 uni on number val ue;

13

14 val ue. x = 100;

15 pr i nt f ( " %s\ n%s\ n%s%d\ n%s%f \ n\ n" ,

16 " Put a val ue i n t he i nt eger member " ,

17 " and pr i nt bot h member s . " ,

18 " i nt : " , val ue. x ,

19 " doubl e: \ n" , val ue. y ) ;

20

21 val ue. y = 100. 0;

22 pr i nt f ( " %s\ n%s\ n%s%d\ n%s%f \ n" ,

23 " Put a val ue i n t he f l oat i ng member " ,

24 " and pr i nt bot h member s . " ,

25 " i nt : " , val ue. x ,

26 " doubl e: \ n" , val ue. y ) ;

27 r et ur n 0;

28 }

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

¤~�=�¦¥��=�V¢¨§��£� � �£�Put a val ue i n t he i nt eger memberand pr i nt bot h member s .i nt : 100doubl e:- 92559592117433136000000000000000000000000000000000000000000000. 00000 Put a val ue i n t he f l oat i ng memberand pr i nt bot h member s .i nt : 0doubl e:100. 000000

Page 39: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

39

2000 Prentice Hall, Inc. All rights reserved.

�������c�®`�� �DU�.�;3d����E��"

• Enumeration– Set of integers represented by identifiers

– Enumeration constants - like symbolicconstants whose values automatically set• Values start at 0 and are incremented by 1

• Values can be set explicitly with =

• Need unique constant names

– Declare variables as usual• Enumeration variables can only assume their

enumeration constant values (not the integerrepresentations)

2000 Prentice Hall, Inc. All rights reserved.

�����m�c�¯`�� �DU�E��3]�� �E��"/$u&;&�)

• Example:enum Mont hs { JAN = 1, FEB, MAR,

APR, MAY, JUN, JUL, AUG, SEP,OCT, NOV, DEC} ;

– Starts at 1, increments by 1

Page 40: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

40

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

{m|~�A�~�+� ���������¢����O�Z�;�����

{m|+{��-��� �;������� ���ª ����� �V«����

�~|~}:��� �

�~|+{�¤������£�

1 / * Fi g. 10. 18: f i g10_18. c

2 Usi ng an enumer at i on t ype * /

3 #i nc l ude <st di o. h>

4

5 enum mont hs { JAN = 1, FEB, MAR, APR, MAY, JUN,

6 JUL, AUG, SEP, OCT, NOV, DEC } ;

7

8 i nt mai n( )

9 {

10 enum mont hs mont h;

11 const char * mont hName[ ] = { " " , " Januar y" , " Febr uar y" ,

12 " Mar ch" , " Apr i l " , " May" ,

13 " June" , " Jul y" , " August " ,

14 " Sept ember " , " Oct ober " ,

15 " November " , " December " } ;

16

17 f or ( mont h = JAN; mont h <= DEC; mont h++ )

18 pr i nt f ( " %2d%11s\ n" , mont h, mont hName[ mont h ] ) ;

19

20 r et ur n 0;

21 }

2000 Prentice Hall, Inc. All rights reserved.

������°2±P��³²´��"��lµ2[��.�;3d³�E�;"

• All data represented internally as sequences of bits– Each bit can be either 0 or 1

– Sequence of 8 bits forms a byte

All 0 bits are set to 1 and all 1 bits are set to 0.One’s complement~

Shifts the bits of the first operand right by the numberof bits specified by the second operand; the method offilling from the left is machine dependent.

right shift>>

Shifts the bits of the first operand left by the number of bitsspecified by the second operand; fill from right with 0 bits.

left shift<<

The bits in the result are set to 1 if exactly one ofthe corresponding bits in the two operands is 1.

bitwise exclusive OR^

The bits in the result are set to 1 if at least one ofthe corresponding bits in the two operands is 1.

bitwise OR|

The bits in the result are set to 1 if thecorresponding bits in the two operands are both 1.

bitwise AND&

DescriptionNameOperator

Page 41: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

41

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

{m|~�m�����~�;���b�� ���~�;����� � �

{m|+{��-��� �;������� ���ª ����� �V«����~�

�~|~�m�����~�;���b�¶�b�V� � �

�~|+{�¤������£�

1 / * Fi g. 10. 9: f i g10_09. c

2 Usi ng t he bi t wi se AND, bi t wi se i ncl usi ve OR, bi t wi se

3 excl us i ve OR and bi t wi se compl ement oper at or s * /

4 #i nc l ude <st di o. h>

5

6 voi d di spl ayBi t s( unsi gned ) ;

7

8 i nt mai n( )

9 {

10 unsi gned number 1, number 2, mask, set Bi t s ;

11

12 number 1 = 65535;

13 mask = 1;

14 pr i nt f ( " The r esul t of combi ni ng t he f ol l owi ng\ n" ) ;

15 di spl ayBi t s( number 1 ) ;

16 di spl ayBi t s( mask ) ;

17 pr i nt f ( " usi ng t he bi t wi se AND oper at or & i s \ n" ) ;

18 di spl ayBi t s( number 1 & mask ) ;

19

20 number 1 = 15;

21 set Bi t s = 241;

22 pr i nt f ( " \ nThe r esul t of combi ni ng t he f ol l owi ng\ n" ) ;

23 di spl ayBi t s( number 1 ) ;

24 di spl ayBi t s( set Bi t s ) ;

25 pr i nt f ( " usi ng t he bi t wi se i nc l usi ve OR oper at or | i s \ n" ) ;

26 di spl ayBi t s( number 1 | set Bi t s ) ;

27

28 number 1 = 139;

29 number 2 = 199;

30 pr i nt f ( " \ nThe r esul t of combi ni ng t he f ol l owi ng\ n" ) ;

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

�~|+{�¤������£�

�b|~�m�����~�;���b������������ �;�����

31 di spl ayBi t s( number 1 ) ;

32 di spl ayBi t s( number 2 ) ;

33 pr i nt f ( " usi ng t he bi t wi se exc l usi ve OR oper at or ^ i s\ n" ) ;

34 di spl ayBi t s( number 1 ^ number 2 ) ;

35

36 number 1 = 21845;

37 pr i nt f ( " \ nThe one’ s compl ement of \ n" ) ;

38 di spl ayBi t s( number 1 ) ;

39 pr i nt f ( " i s \ n" ) ;

40 di spl ayBi t s( ~number 1 ) ;

41

42 r et ur n 0;

43 }

44

45 voi d di spl ayBi t s( unsi gned val ue )

46 {

47 unsi gned c , di spl ayMask = 1 << 31;

48

49 pr i nt f ( " %7u = " , val ue ) ;

50

51 f or ( c = 1; c <= 32; c++ ) {

52 put char ( val ue & di spl ayMask ? ’ 1’ : ’ 0’ ) ;

53 val ue <<= 1;

54

55 i f ( c % 8 == 0 )

56 put char ( ’ ’ ) ;

57 }

58

59 put char ( ’ \ n’ ) ;

60 }

MASK created with only one set bit, i.e.

(10000000 00000000 0000000000000000)

The MASK is constantly ANDed with val ue.

MASK only contains one bit, so if the ANDreturns true it means val ue must have thatbit.

val ue is then shifted to test the next bit.

Page 42: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

42

2000 Prentice Hall, Inc. All rights reserved.

r�sutwv x y@z

¤~�=�¦¥��=�V¢¨§��£� � �£�

The r esul t of combi ni ng t he f ol l owi ng 65535 = 00000000 00000000 11111111 11111111 1 = 00000000 00000000 00000000 00000001usi ng t he bi t wi se AND oper at or & i s 1 = 00000000 00000000 00000000 00000001 The r esul t of combi ni ng t he f ol l owi ng 15 = 00000000 00000000 00000000 00001111 241 = 00000000 00000000 00000000 11110001usi ng t he bi t wi se i ncl usi ve OR oper at or | i s 255 = 00000000 00000000 00000000 11111111 The r esul t of combi ni ng t he f ol l owi ng 139 = 00000000 00000000 00000000 10001011 199 = 00000000 00000000 00000000 11000111usi ng t he bi t wi se excl usi ve OR oper at or ^ i s 76 = 00000000 00000000 00000000 01001100 The one' s compl ement of 21845 = 00000000 00000000 01010101 01010101i s4294945450 = 11111111 11111111 10101010 10101010

2000 Prentice Hall, Inc. All rights reserved.

��������� ±P��^T·���E4 \]"

• Bit field– Member of a structure whose size (in bits) has been specified

– Enable better memory utilization

– Must be declared as i nt or unsi gned

– Cannot access individual bits

• Declaring bit fields– Follow unsi gned or i nt member with a colon (:) and

an integer constant representing the width of the field

– Example:st r uct Bi t Car d {

unsi gned f ace : 4;

unsi gned sui t : 2;

unsi gned col or : 1;

} ;

Page 43: Chapter 7 - Pointerscommunity.wvu.edu/~daadjeroh/classes/cs350/... · – Pointers contain address of a variable that has a specific value (indirect reference) – Indirection - referencing

43

2000 Prentice Hall, Inc. All rights reserved.

¸�¹�ºm¸�¹ »M¼�½^¾�¼ ¿EÀ�ÁdÂ%Ã'Ä0Ä=Å

• Unnamed bit field– Field used as padding in the structure

– Nothing may be stored in the bitsst r uct Exampl e {

unsi gned a : 13;

unsi gned : 3;

unsi gned b : 4;

}

– Unnamed bit field with zero width aligns nextbit field to a new storage unit boundary