csc 211 data structures lecture 5

62
1 CSC 211 Data Structures Lecture 5 Dr. Iftikhar Azim Niaz [email protected] 1

Upload: binta

Post on 23-Feb-2016

66 views

Category:

Documents


6 download

DESCRIPTION

CSC 211 Data Structures Lecture 5. Dr. Iftikhar Azim Niaz [email protected]. 1. Last Lecture Summary. Data type and Data structure Data types in C Arrays Declaration Initialization Representation Operations Arrays and functions Pointers Declaration, Initialization - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSC 211 Data Structures Lecture 5

1

CSC 211Data Structures

Lecture 5

Dr. Iftikhar Azim [email protected]

1

Page 2: CSC 211 Data Structures Lecture 5

2

Last Lecture Summary Data type and Data structure Data types in C Arrays

Declaration Initialization Representation Operations Arrays and functions

Pointers Declaration, Initialization Arrays and pointers

2

Page 3: CSC 211 Data Structures Lecture 5

3

Objectives Overview Concept of Pointer Pointer operators

Address and Indirection Pointer Arithmetic Pointer and functions

Pass by Value Pass by Reference

Pointer and Arrays

Page 4: CSC 211 Data Structures Lecture 5

4

Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings A pointer, like an integer, holds a number

Interpreted as the address of another object Must be declared with its associated type:

e.g., “pointer to integer”, “pointer to character”, etc. int *x;

Useful for: Dynamic objects

Page 5: CSC 211 Data Structures Lecture 5

5

Pointer Indirection Accessing an object through a pointer is called

indirection The “address-of” operator (&)obtains an

object’s address The “de-referencing” operator (*) refers to the

object the pointer pointed at

Page 6: CSC 211 Data Structures Lecture 5

6

Pointer Diagram

0012FF88 8

ip i (@0012FF88)

int i = 8; // declaring integer variableint *ip; // declaring pointer variableip = &i; // assigning address of i to ipcout<<*ip; // output value pointed to by ip

Pointer Variable Integer Variable

Page 7: CSC 211 Data Structures Lecture 5

7

Pointer Variable Declarations and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct

reference)

Pointers contain address of a variable that has a specific value (indirect reference)

Indirection – referencing a pointer value

  count

7

count

7

countPtr

Page 8: CSC 211 Data Structures Lecture 5

8

Pointer Variable Declarations and Initialization Pointer declarations * used with pointer variables

int *myPtr; Declares a pointer to an int (pointer of type int *) Multiple pointers require using a * before each

variable declarationint *myPtr1, *myPtr2;

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

0 or NULL – points to nothing (NULL preferred)

Page 9: CSC 211 Data Structures Lecture 5

9

Pointer Operators & (address operator)

Returns address of operandint y = 5;int *yPtr; yPtr = &y; // yPtr gets address of yyPtr “points to” y

yPtry5

yptr

500000 600000

y

600000 5

Address of y is value of yptr

Page 10: CSC 211 Data Structures Lecture 5

10

Pointer Operators * (indirection/dereferencing operator)

Returns a synonym/alias of what its operand points to

*yptr returns y (because yptr points to y) * can be used for assignment

Returns alias to an object*yptr = 7; // changes y to 7

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

* and & are inverses They cancel each other out

Page 11: CSC 211 Data Structures Lecture 5

11

void main(void) {int x, y;int *p, *q;p = &x;q = &y;*p = 2;y = *p;*q = *p;p = q;

x

yp

q

Pointer Example

Page 12: CSC 211 Data Structures Lecture 5

12

void main(void) {int x, y;int *p, *q;p = &x;q = &y;*p = 2;y = *p;*q = *p;p = q;

x

yp

q

Pointer Example (cont..)

Page 13: CSC 211 Data Structures Lecture 5

13

void main(void) {int x, y;int *p, *q;p = &x;q = &y;*p = 2;y = *p;*q = *p;p = q;

x

yp

q

Pointer Example (cont..)

Page 14: CSC 211 Data Structures Lecture 5

14

void main(void) {int x, y;int *p, *q;p = &x;q = &y;*p = 2;y = *p;*q = *p;p = q;

2x

yp

q

Pointer Example (cont..)

Page 15: CSC 211 Data Structures Lecture 5

15

void main(void) {int x, y;int *p, *q;p = &x;q = &y;*p = 2;y = *p;*q = *p;p = q;

2

2x

yp

q

Pointer Example (cont..)

Page 16: CSC 211 Data Structures Lecture 5

16

Pointer Declaration Examples double * p1; double* p2;

// think p2 is of type "double*“ double *p3;

// think *p3 is a double double x = 4.5; p1 = &x;

// p1 holds the memory address of x int * q1;

// q1 can hold the memory address of ints only q1 = &x;

// error - x is a double, q1 only works with int int m = 4; q1 = &m;

// legal - types match

Page 17: CSC 211 Data Structures Lecture 5

17

Pointer Exampleint x=3,y=4,z=5,*xp,*yp,*zp;xp=&z; // xp holds the address of zyp=&(*xp); // yp points the pointer variable xp zp=&(*yp); // zp points the pointer variable yp so all the pointers xp, yp and zp

point to zcout<<"value in z...."<<z; cout<<"\n value in *yp......"<<*yp;cout<<"\n value in *xp......"<<*xp; cout<<"\n valuein *zp...."<<*zp;*yp=x; //now when we change pointer variable yp it will change the value of z;cout<<"\n\n value in z...."<<z; cout<<"\n value in *yp......"<<*yp;cout<<"\n value in *xp......"<<*xp; cout<<"\n valuein *zp...."<<*zp;*zp=1; //zp also points z directly or indirectly so it will //also change value of z’cout<<"\n \n value in z...."<<z; cout<<"\n value in *yp......"<<*yp;cout<<"\n value in *xp......"<<*xp; cout<<"\n valuein *zp...."<<*zp;

Output(5,3,1)

Page 18: CSC 211 Data Structures Lecture 5

1. Declare variables

2 Initialize variables

3. Print

Program Output

1 /* Fig. 7.4: fig07_04.c2 Using the & and * operators */3 #include <stdio.h>45 int main()6 {7 int a; /* a is an integer */8 int *aPtr; /* aPtr is a pointer to an integer */910 a = 7;11 aPtr = &a; /* aPtr set to address of a */1213 printf( "The address of a is %p" 14 "\nThe value of aPtr is %p", &a, aPtr );1516 printf( "\n\nThe value of a is %d" 17 "\nThe value of *aPtr is %d", a, *aPtr );1819 printf( "\n\nShowing that * and & are inverses of "20 "each other.\n&*aPtr = %p" 21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr );2223 return 0;24 }

The address of a is 0012FF88The value of aPtr is 0012FF88The value of a is 7The value of *aPtr is 7Proving that * and & are complements of each other.&*aPtr = 0012FF88*&aPtr = 0012FF88

The address of a is the value of aPtr.

The * operator returns an alias to what its operand points to. aPtr points to a, so *aPtr returns a.

Notice how * and & are inverses

Page 19: CSC 211 Data Structures Lecture 5

19

Review of pointers A pointer is just a memory location. A memory location is simply an integer value,

that we interpret as an address in memory. The contents at a particular memory location

are just a collection of bits – there’s nothing special about them that makes them ints, chars, etc. How you want to interpret the bits is up to you. Is this... an int value?

... a pointer to a memory address?

... a series of char values?

0xfe4a10c5

Page 20: CSC 211 Data Structures Lecture 5

20

Review of pointer variables A pointer variable is just a variable, that

contains a value that we interpret as a memory address.

Just like an uninitialized int variable holds some arbitrary “garbage” value,an uninitialized pointer variable points to some arbitrary “garbage address”

char *m;

(char *)

m

Page 21: CSC 211 Data Structures Lecture 5

21

Following a “garbage” pointer What will happen? Depends on what the arbitrary memory address is: If it’s an address to memory that the OS has not

allocated to our program, we get a segmentation fault If it’s a nonexistent address, we get a bus error Some systems require multibyte data items, like ints,

to be aligned: for instance, an int may have to start at an even-numbered address, or an address that’s a multiple of 4. If our access violates a restriction like this, we get a bus error

If we’re really unlucky, we’ll access memory that is allocated for our program –We can then proceed to destroy our own data!

Page 22: CSC 211 Data Structures Lecture 5

22

Testing whether a pointer points to something meaningful?

There is a special pointer value NULL, that signifies “pointing to nothing”. You can also use the value 0.

char *m = NULL;...if (m) { ... safe to follow the pointer ... }

Here, m is used as a Boolean value If m is “false”, aka 0, aka NULL, it is not pointing to anything Otherwise, it is (presumably) pointing to something good Note: It is up to the programmer to assign NULL values

when necessary

Page 23: CSC 211 Data Structures Lecture 5

23

Indirection operator * Moves from address to contents

char *m = ″dog″;

char result = *m;

m gives an address of a char*m instructs us to take the contents of that addressresult gets the value ′d′

(char *)

m

d(char)

o(char)

g(char)

NUL(char)

(char)

result

d(char)

Page 24: CSC 211 Data Structures Lecture 5

24

Address operator & Instead of contents, returns the address

char *m = ″dog″,**pm = &m;

pm needs a value of type char ** Can we give it *m? No – type is char Can we give it m? No – type is char * &m gives it the right value – the address of a char * value

(char *)

(char **)

m

pm

d(char)

o(char)

g(char)

NUL(char)

Page 25: CSC 211 Data Structures Lecture 5

25

Pointer arithmetic C allows pointer values to be incremented by

integer values

char *m = ″dog″;

char result = *(m + 1);

m gives an address of a char(m + 1) gives the char one byte higher *(m + 1) instructs us to take the contents of that addressresult gets the value ′o′

(char *)

m

d(char)

o(char)

g(char)

NUL(char)

(char)

result

o(char)

Page 26: CSC 211 Data Structures Lecture 5

26

Pointer arithmetic A slightly more complex example:

char *m = ″dog″;

char result = *++m;

m gives an address of a char++m changes m, to the address one byte higher,

and returns the new address*++m instructs us to take the contents of that locationresult gets the value ′o′

(char *)

m

d(char)

o(char)

g(char)

NUL(char)

(char)

result

o(char)

Page 27: CSC 211 Data Structures Lecture 5

27

Pointer arithmetic How about multibyte values?

Q: Each char value occupies exactly one byte, so obviously incrementing the pointer by one takes you to a new char value...But what about types like int that span more than one byte?

A: C “does the right thing”: increments the pointer bythe size of one int value

int a[2] = {17, 42};int *m = a;int result = *++m;

(int *)

m(char)

result

42(int)

17(int)

42(int)

Page 28: CSC 211 Data Structures Lecture 5

28

Pointer Expressions and Pointer Arithmetic Arithmetic operations can be performed on pointers 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 

Page 29: CSC 211 Data Structures Lecture 5

29

Pointer Expressions and Pointer Arithmetic 5 element int array on machine with 4 byte ints vPtr points to first element v[ 0 ]

at location 3000 (vPtr = 3000) vPtr += 2; sets vPtr to 3008

vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 byte ints, so it points to address 3008

pointer variable vPtr

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

3000 3004 3008 3012 3016location

 

Page 30: CSC 211 Data Structures Lecture 5

30

Pointer Expressions and Pointer Arithmetic Subtracting pointers Returns number of elements from one to the other.

IfvPtr2 = v[ 2 ];vPtr = v[ 0 ];

vPtr2 - vPtr would produce 2 Pointer comparison ( <, == , > )

See which pointer points to the higher numbered array element

Also, see if a pointer points to 0

Page 31: CSC 211 Data Structures Lecture 5

31

Pointer Expressions and Pointer Arithmetic Pointers of the same type can be assigned to each other If not the same type, a cast operator must be used Exception: pointer to void (type void *)

Generic pointer, represents any type No casting needed to convert a pointer to void pointer void pointers cannot be dereferenced

Page 32: CSC 211 Data Structures Lecture 5

32

Pointers to Functions 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

Page 33: CSC 211 Data Structures Lecture 5

33

Pointers to Functions Example: bubblesort

Function bubble takes a function pointer bubble calls this helper function this determines ascending or descending sorting

The argument in bubblesort for the function pointer:

bool ( *compare )( int, int )tells bubblesort to expect a pointer to a function that takes two

ints and returns a bool If the parentheses were left out:

bool *compare( int, int ) Declares a function that receives two integers and returns

a pointer to a bool

Page 34: CSC 211 Data Structures Lecture 5

1. Initialize array

2. Prompt for ascending or descending sorting

2.1 Put appropriate function pointer into bubblesort

2.2 Call bubble

3. Print results

1 /* Fig. 7.26: fig07_26.c2 Multipurpose sorting program using function pointers */3 #include <stdio.h>4 #define SIZE 105 void bubble( int [], const int, int (*)( int, int ) );6 int ascending( int, int );7 int descending( int, int );89 int main()10 {11 12 int order, 13 counter,14 a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };1516 printf( "Enter 1 to sort in ascending order,\n" 17 "Enter 2 to sort in descending order: " );18 scanf( "%d", &order );19 printf( "\nData items in original order\n" );20 21 for ( counter = 0; counter < SIZE; counter++ )22 printf( "%5d", a[ counter ] );2324 if ( order == 1 ) {25 bubble( a, SIZE, ascending );26 printf( "\nData items in ascending order\n" );27 }28 else {29 bubble( a, SIZE, descending );30 printf( "\nData items in descending order\n" );31 }32

Notice the function pointer parameter.

Page 35: CSC 211 Data Structures Lecture 5

3.1 Define functions

33 for ( counter = 0; counter < SIZE; counter++ )34 printf( "%5d", a[ counter ] ); 3536 printf( "\n" );3738 return 0;39 }4041 void bubble( int work[], const int size, 42 int (*compare)( int, int ) )43 {44 int pass, count;4546 void swap( int *, int * );4748 for ( pass = 1; pass < size; pass++ )4950 for ( count = 0; count < size - 1; count++ )5152 if ( (*compare)( work[ count ], work[ count + 1 ] ) )53 swap( &work[ count ], &work[ count + 1 ] );54 }5556 void swap( int *element1Ptr, int *element2Ptr )57 {58 int temp;5960 temp = *element1Ptr;61 *element1Ptr = *element2Ptr;62 *element2Ptr = temp;63 }64

ascending and descending return true or false. bubble calls swap if the function call returns true.

Notice how function pointers are called using the dereferencing operator. The * is not required, but emphasizes that compare is a function pointer and not a function.

Page 36: CSC 211 Data Structures Lecture 5

3.1 Define functions

Program Output

65int ascending( int a, int b )66{67 return b < a; /* swap if b is less than a */68}6970int descending( int a, int b )71{72 return b > a; /* swap if b is greater than a */73}

Enter 1 to sort in ascending order,Enter 2 to sort in descending order: 1 Data items in original order 2 6 4 8 10 12 89 68 45 37Data items in ascending order 2 4 6 8 10 12 37 45 68 89Enter 1 to sort in ascending order,Enter 2 to sort in descending order: 2 Data items in original order 2 6 4 8 10 12 89 68 45 37Data items in descending order 89 68 45 37 12 10 8 6 4 2

Page 37: CSC 211 Data Structures Lecture 5

37

Reference Semantics Pass/call by reference

When a function parameter is passed as a pointer Changing the parameter changes the original

argument Arrays are pointers Arrays as Arguments structs are usually passed as pointers

Page 38: CSC 211 Data Structures Lecture 5

38

Pass by value void by_value(int a, int b, int c);void main() { int x = 2, y = 4, z = 6;cout<<"\nBefore calling by_value(), x y z "<<x<<y<<z; by_value(x, y, z);cout<<"\nAfter calling by_value(), x , y , z "<<x<<y<<z; } void by_value(int a, int b, int c) { a = 0; b = 0; c = 0; }

Page 39: CSC 211 Data Structures Lecture 5

39

void by_ref(int *a, int *b, int *c); void main(){ int x = 2, y = 4, z = 6; by_ref(&x, &y, &z); //Passing address of x,y and z; cout<<"\nAfter calling by_ref(), x , y , z = "<<x<<y<<z; } void by_ref(int *a, int *b, int *c) //*a holds the value at address &x { *a = 0; //will change the value at the address of x *b = 0; //will change the value at the address of y *c = 0; //will change the value at the address of z }

Page 40: CSC 211 Data Structures Lecture 5

40

Example: initializing an array#define N_VALUES 5float values[N_VALUES];

float *vp;for ( vp = &values[0]; vp < &values[N_VALUES]; )

*vp++ = 0;

(float *)

vp

(float) (float) (float) (float) (float)

&values[0]&values[N_VALUES]

values

(float [])0

(float)0

(float)0

(float)0

(float)0

(float) (done!)

Page 41: CSC 211 Data Structures Lecture 5

41

A note on assignment: Rvalues vs. Lvalues

What’s really going on in an assignment? Different things happen on either side of the =

int a = 17, b = 42;

b = a;

17(int)

a

42(int)

b

a is the “rvalue” (right value) We go to the address given by a...

and get the contents (17)

b is the “lvalue” (left value) We go to the address given by b...and get the contents?

No! We don’t care about 42!We just want the address of b – to store 17 into

Page 42: CSC 211 Data Structures Lecture 5

42

A note on assignment: Rvalues vs. Lvalues This explains a certain “asymmetry” in assignments

involving pointers:

char *m = NULL, **pm = NULL;

m = “dog”;

pm = &m;

(char *)

(char **)

m

pm

d(char)

o(char)

g(char)

NUL(char)

Here, m is an lvalue – It’s understood that the address of m is what’s needed

Once again, we need the address of m –but since it’s an rvalue, just plain m will give the contents of m

– use & to get the address instead

Page 43: CSC 211 Data Structures Lecture 5

43

Example: strcpy “string copy”char *strcpy(char *dest, const char *src)

(assume that) src points to a sequence of char values that we wish to copy, terminated by NUL

(assume that) dest points to an accessible portion of memory large enough to hold the copied chars

strcpy copies the char values of src to the memory pointed to by dest

strcpy also gives dest as a return value

Page 44: CSC 211 Data Structures Lecture 5

44

Example: strcpy “string copy”char *strcpy(char *dest, const char *src) {const char *p;char *q;for(p = src, q = dest; *p != '\0'; p++, q++)

*q = *p;*q = '\0';return dest;

}

d(char)

o(char)

g(char)

NUL(char)

(char) (char) (char) (char)

(char *)

src

(char *)

dest

(char *) (char *)p q

d(char)

o(char)

g(char)

NUL(char)

Page 45: CSC 211 Data Structures Lecture 5

45

Pointer subtraction and relational operations

Only meaningful in special context: where you have two pointers referencing different elements of the same array q – p gives the difference (in number of array elements,

not number of bytes between p and q (in this example, 2) p < q returns 1 if p has a lower address than q; else 0

(in this example, it returns 1)

(float) (float) (float) (float) (float)(float) (float) (float) (float) (float)

(float *)

p(float *)

q

Page 46: CSC 211 Data Structures Lecture 5

46

Calling Functions by Reference 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 functionvoid double( int *number ) {

*number = 2 * ( *number ); }

*number used as nickname for the variable passed

Page 47: CSC 211 Data Structures Lecture 5

1. Function prototype

1.1 Initialize variables

2. Call function

3. Define function

Program Output

1 /* Fig. 7.7: fig07_07.c2 Cube a variable using call-by-reference 3 with a pointer argument */45 #include <stdio.h>67 void cubeByReference( int * ); /* prototype */89 int main()10 {11 int number = 5;1213 printf( "The original value of number is %d", number );14 cubeByReference( &number );15 printf( "\nThe new value of number is %d\n", number );1617 return 0;18 }1920 void cubeByReference( int *nPtr )21 {22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */23 }

The original value of number is 5The new value of number is 125

Notice how the address of number is given - cubeByReference expects a pointer (an address of a variable).

Inside cubeByReference, *nPtr is used (*nPtr is number).

Notice that the function prototype takes a pointer to an integer (int *).

Page 48: CSC 211 Data Structures Lecture 5

48

Using the const Qualifier with Pointers const qualifier Variable cannot be changed Use const if function does not need to change a variable Attempting to change a const variable produces an error

const pointers Point to a constant memory location Must be initialized when declared int *const myPtr = &x;

Type int *const – constant pointer to an int const int *myPtr = &x;

Regular pointer to a const int const int *const Ptr = &x;

const pointer to a const int x can be changed, but not *Ptr

Page 49: CSC 211 Data Structures Lecture 5

1. Declare variables

1.1 Declare const pointer to an int

2. Change *ptr (which is x)

2.1 Attempt to change ptr

3. Output

Program Output

1 /* Fig. 7.13: fig07_13.c2 Attempting to modify a constant pointer to3 non-constant data */45 #include <stdio.h>67 int main()8 {9 int x, y;1011 int * const ptr = &x; /* ptr is a constant pointer to an 12 integer. An integer can be modified13 through ptr, but ptr always points 14 to the same memory location. */15 *ptr = 7;16 ptr = &y;1718 return 0;19}FIG07_13.c:Error E2024 FIG07_13.c 16: Cannot modify a const object in function main*** 1 errors in Compile ***

Changing *ptr is allowed – x is not a constant.

Changing ptr is an error – ptr is a constant pointer.

Page 50: CSC 211 Data Structures Lecture 5

50

The Relationship Between Pointers and Arrays

Arrays and pointers closely related Array name like a constant pointer Pointers can do array subscripting operations

Declare an array b[ 5 ] and a pointer bPtr To set them equal to one another use:

bPtr = b; The array name (b) is actually the address of first element

of the array b[ 5 ]bPtr = &b[ 0 ]

Explicitly assigns bPtr to address of first element of b

Page 51: CSC 211 Data Structures Lecture 5

51

The Relationship Between Pointers and Arrays Element b[ 3 ]

Can be accessed by *( bPtr + 3 ) Where n is the offset. Called pointer/offset notation

Can be accessed by bptr[ 3 ] Called pointer/subscript notation bPtr[ 3 ] same as b[ 3 ]

Can be accessed by performing pointer arithmetic on the array itself*( b + 3 )

Page 52: CSC 211 Data Structures Lecture 5

52

Arrays of Pointers Arrays can contain pointers For example: an array of strings

char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };

Strings are pointers to the first character char * – each element of suit is a pointer to a char The strings are not actually stored in the array suit,

only pointers to the strings are stored

suit array has a fixed size, but strings can be of any size

suit[3]suit[2]suit[1]suit[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’

 

Page 53: CSC 211 Data Structures Lecture 5

53

Arrays to functions #include <stdio.h> #include <iostream.h> #include<conio.h> int addNumbers(int fiveNumbers[]); /* declare function */ void main() { int array[5]; int i; cout<<"Enter 5 integers separated by spaces: "; for(i=0 ; i<5 ; i++) { cin>>array[i]; } cout<<”\nTheir sum is: "<<addNumbers(array); Getche(); } int addNumbers(int fiveNumbers[]) { /* define function */ int sum = 0; int i; for(i=0 ; i<5 ; i++) { sum+=fiveNumbers[i]; /* work out the total */ } return sum; /* return the total */ }

Page 54: CSC 211 Data Structures Lecture 5

54

Case Study: A Card Shuffling and Dealing Simulation

Card shuffling program Use array of pointers to strings Use double scripted array (suit, face)

The numbers 1-52 go into the array Representing the order in which the cards are dealt

deck[ 2 ][ 12 ] represents the King of Clubs

HeartsDiamondsClubsSpades

0123

Ace Two ThreeFourFiveSix SevenEight

NineTen JackQueenKing0 1 2 3 4 5 6 7 8 9 10 11 12

Clubs King

 

Page 55: CSC 211 Data Structures Lecture 5

55

Case Study: A Card Shuffling and Dealing Simulation

Pseudocode - Top level: Shuffle and deal 52 cards

Initialize the suit arrayInitialize the face arrayInitialize the deck array

Shuffle the deck

Deal 52 cards

For each of the 52 cards

Place card number in randomly selected unoccupied slot of deck

For each of the 52 cards

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

Choose slot of deck randomly

While chosen slot of deck has been previously chosen

Choose slot of deck randomlyPlace card number in chosen slot of deck

For each slot of the deck array

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

Second refinementThird refinement

First refinement

Page 56: CSC 211 Data Structures Lecture 5

56

Case Study: A Card Shuffling and Dealing Simulation

Pseudocode Top level:

Shuffle and deal 52 cards First refinement:

Initialize the suit arrayInitialize the face arrayInitialize the deck arrayShuffle the deckDeal 52 cards

Page 57: CSC 211 Data Structures Lecture 5

57

Case Study: A Card Shuffling and Dealing Simulation

Second refinement

Convert shuffle the deck toFor each of the 52 cards

Place card number in randomly selected unoccupied slot of deck

Convert deal 52 cards toFor each of the 52 cards

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

Page 58: CSC 211 Data Structures Lecture 5

58

Case Study: A Card Shuffling and Dealing Simulation

Third refinement

Convert shuffle the deck toChoose slot of deck randomly While chosen slot of deck has been previously chosen

Choose slot of deck randomlyPlace card number in chosen slot of deck

Convert deal 52 cards toFor each slot of the deck array

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

Page 59: CSC 211 Data Structures Lecture 5

1. Initialize suit and face arrays

1.1 Initialize deck array

2. Call function shuffle

2.1 Call function deal

3. Define functions

1 /* Fig. 7.24: fig07_24.c2 Card shuffling dealing program */3 #include <stdio.h>4 #include <stdlib.h>5 #include <time.h>67 void shuffle( int [][ 13 ] );8 void deal( const int [][ 13 ], const char *[], const char *[] );910 int main()11 {12 const char *suit[ 4 ] = 13 { "Hearts", "Diamonds", "Clubs", "Spades" };14 const char *face[ 13 ] = 15 { "Ace", "Deuce", "Three", "Four",16 "Five", "Six", "Seven", "Eight",17 "Nine", "Ten", "Jack", "Queen", "King" };18 int deck[ 4 ][ 13 ] = { 0 };1920 srand( time( 0 ) );2122 shuffle( deck );23 deal( deck, face, suit );2425 return 0;26 }2728 void shuffle( int wDeck[][ 13 ] )29 {30 int row, column, card;3132 for ( card = 1; card <= 52; card++ ) {

Page 60: CSC 211 Data Structures Lecture 5

3. Define functions

33 do {34 row = rand() % 4;35 column = rand() % 13;36 } while( wDeck[ row ][ column ] != 0 );3738 wDeck[ row ][ column ] = card;39 }40 }4142 void deal( const int wDeck[][ 13 ], const char *wFace[],43 const char *wSuit[] )44 {45 int card, row, column;4647 for ( card = 1; card <= 52; card++ )4849 for ( row = 0; row <= 3; row++ )5051 for ( column = 0; column <= 12; column++ )5253 if ( wDeck[ row ][ column ] == card )54 printf( "%5s of %-8s%c",55 wFace[ column ], wSuit[ row ],56 card % 2 == 0 ? '\n' : '\t' );57 }

The numbers 1-52 are randomly placed into the deck array.

Searches deck for the card number, then prints the face and suit.

Page 61: CSC 211 Data Structures Lecture 5

Program Output Six of Clubs Seven of Diamonds Ace of Spades Ace of Diamonds Ace of Hearts Queen of DiamondsQueen of Clubs Seven of Hearts Ten of Hearts Deuce of Clubs Ten of Spades Three of Spades Ten of Diamonds Four of Spades Four of Diamonds Ten of Clubs Six of Diamonds Six of SpadesEight of Hearts Three of Diamonds Nine of Hearts Three of HeartsDeuce of Spades Six of Hearts Five of Clubs Eight of ClubsDeuce of Diamonds Eight of Spades Five of Spades King of Clubs King of Diamonds Jack of SpadesDeuce of Hearts Queen of Hearts Ace of Clubs King of SpadesThree of Clubs King of Hearts Nine of Clubs Nine of Spades Four of Hearts Queen of SpadesEight of Diamonds Nine of Diamonds Jack of Diamonds Seven of Clubs Five of Hearts Five of Diamonds Four of Clubs Jack of Hearts Jack of Clubs Seven of Spades

Page 62: CSC 211 Data Structures Lecture 5

62

Summary Concept of Pointer Pointer operators

Address and Indirection Pointer Arithmetic Pointer and functions

Pass by Value Pass by Reference

Pointer and Arrays