bİl 133 – algoritma ve programlama chapter 8: arrays and ... · searching and sorting an array...

40
Chapter 8: Arrays and pointers BİL 133 – Algoritma ve Programlama Maltepe University Computer Engineering Department

Upload: nguyencong

Post on 02-May-2019

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Chapter 8: Arrays and pointers

BİL 133 – Algoritma ve Programlama

Maltepe University

Computer Engineering Department

Page 2: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Basics int * ptr1, * ptr2;

int a[10];

ptr1 = &a[2];

ptr2 = a; // equivalent to ptr2 = &a[0];

• An array variable is actually a pointer to

the first element of the array.

• ptr2 points to the first element of the

array and get others by offset.

• Referring a[i] is same as referring *(a+i).

a

a+1

a+2

.

.

?

?

?

?

?

?

?

?

0

1

2

3

4

5

6

7

Memory Addresses

2

Page 3: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Array Elements as Function arguments

• If we want to print the ith element of the array x[i], then

we can do the following:

printf(”%d\n”, x[i]);

scanf(”%d”, &x[i]);

• We can also pass array elements as arguments to

functions that we write. For example:

swap1(x[i], x[i+1]);

swap2(&x[i], &x[i+1]);

3

Page 4: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Having arrays as function arguments

• Besides passing individual array elements to functions, we can write functions that take entire arrays as arguments.

• There are several ways of passing arrays to functions but in each case we only pass the address of the array.

• This is very similar to what we did during “passing variables by reference…”

• As we are not passing a copy of the array – any changes to the array made within the function will also effect the original array.

• When an array name with no subscript appears in the argument list of a function call, what is actually stored in the function’s corresponding parameter is the address of the array. Example,

int a[10]; foo(a); foo(&a[0]); // same as above

4

Page 5: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Array Arguments

• We can also pass an entire array as the input

argument for a function.

• However, the function does not copy the array

but just manipulates the original array.

– An assignment to one of the array elements by a

statement in the function changes the contents of the

original array.

5

Page 6: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Passing array as function parameter

• Array names are pointers.

• The name of an array contain the address of its initial element, a = &a[0];

• Passing an array as function argument copies the value of the pointer to the formal array parameter and points to the same location.

• Where is the array actually located?

– At the data area of the function that declared it.

– For an array declared as formal parameter, space is allocated in the function data area only for the address of the initial array element of the array passed as actual argument.

6

Page 7: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Using arrays in formal parameter list void foo(int x[10])

• Store the address of the corresponding array argument (a in

previous slide) to variable x, compiler ignores 10 since x is a

pointer.

void foo(int x[])

• This is just a different format to make code easy to read, for

compiler this format or the others have the same meaning.

void foo(int *x)

• Function foo can take any integer array as argument.

• You should also give the size as a parameter to make the

function more portable.

• void foo(int *x, int size)

7

Page 8: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Arrays as Input Arguments

• ANSI C provides a qualifier that we can include in the declaration of the array formal parameter in order to notify the C complier that the array is only an input to the function and that the function does not intend to modify the array.

• This qualifier allows the compiler to mark as an error any attempt to change an array element within the function.

void foo(const int x[], int size) • The const tells C not to allow any element of the array x

to change in the function foo.

8

Page 9: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

C code Example

int main(void){

int a[5]={1,2,3,4,5};

int i;

clear1(a,5);

clear2(a,5);

for(i=0; i<5; i=i+1)

printf("%d ", a[i]);

return 0;

}

void clear1(int x[], int size){

int i;

for(i=0; i<size; i=i+1)

x[i] = 0;

}

void clear2(int *x, int size){

int *p;

for(p=x; p<(x+size); p=p+1)

// for(p=&x[0]; p<&x[size]; p=p+1)

*p = 0;

}

9

Page 10: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

An Example of Array Arguments

• We have the flexibility to pass an array of any

size to the function.

– Because C does not allocate any memory space

for the array, and thus the compiler does not need

to know the size. int list[] is

the declaration for

passing an int

array

10

Page 11: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Data Areas After Calling fill_array (x, 5, 1);

The value of each element in the

original array are changed to 1.

11

Page 12: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Alternative Formats of Array

Arguments • fill_array(x, 5, 1) is the same as

fill_array(&x[0], 5, 1).

– This call may lead to misunderstanding of the reader.

• In the declaration for function fill_array,

we can declare the array argument as either

– int list[] or int *list.

• If you wish to prevent the modification of the

array argument, you can write

– fill_array(const int list[], …)

12

Page 13: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Using Array Elements as Function

Arguments (1)

• Suppose that we have a function prototype as

shown below.

– void do_it(double arg_1, double

*arg2_p, double *arg3_p);

• Let x be an array of type double elements.

• We can call the function do_it as follows.

– do_it(x[0], &x[1], &x[2]);

• The modification on arg2_p and arg3_p will

change the values of x[1] and x[2]. 13

Page 14: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Using Array Elements as Function

Arguments (2)

arg_1 has a

copy of the

value from x[0]

arg_3 is a pointer

pointed to the

memory of x[2]. 14

Page 15: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Returning an Array from a function(1)

• Returning arrays should work too - right?

int a[5];

a = foo();

…..

int* foo() {

int c[5] = {1,2,3,4,5};

return c;

}

• Wrong! In C, it is not legal for a function’s return

type to be an array.

15

Page 16: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Returning an Array from a function(2)

• Type problem between int[] and int*

– a is a constant pointer type, you can’t change it.

• Array c is stored in function foo’s stack frame.

– Return just copies the pointer, not the array.

– Memory where the array c resides may be overwritten once

function foo finishes its execution.

• To do it properly

– Pass an array as a function argument from your calling

function and modify it inside the called function.

16

Page 17: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Returning an Array Result

• The add_arrays function computes the sum

of corresponding elements in arrays ar1 and

ar2, and then stores results into ar3.

Input array arguments

Output array

arguments

17

Page 18: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Memory for calling

add_arrays(x, y, x_plus_y)

Indirectly read the values of array

x

Indirectly read the values of array y

Indirectly write the values of x+y

into x_plus_y 18

Page 19: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Searching and Sorting an Array

• Sometimes we may need to

– search a particular value in an array, or

– sort an array to rearrange the array elements in

numerical order.

• Commonly used searching methods:

– Sequential search, binary search, etc.

• Commonly used sorting methods:

– Selection sort, bubble sort, quick sort, etc.

19

Page 20: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Sequential Search in an Array

target is the value we want to

locate in the array

Traverse the array to look for

the value identical to target.

20

Page 21: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Selection Sort in an Array

• Selection sort is an

intuitive sorting

algorithm.

– Find the index of the

smallest element in

the array.

– Swap the smallest

element with the first

element.

– Repeat the above

steps for the 2nd, 3rd,

…, smallest elements.

Not included

21

Page 22: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

A Function for Selection Sort

Suppose we have a function that

can find the minimal element.

Swap the minimal

element with the

previous larger

element. 22

Page 23: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Multidimensional Arrays

• A multidimensional array is an array with two or more dimensions.

• We will use two-dimensional arrays to represent tables of data, matrices, and other two-dimensional objects.

• Thus int x[3][3] would define a three by three matrix that holds integers.

• Initialization is bit different

int x[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};

• Both indices starts at 0.

• Think of it as x[rows][cols]. x[0][0]=1 x[0][1]=2 x[0][2]=3

x[1][0]=4 x[1][1]=5 x[1][2]=6

x[2][0]=7 x[2][1]=8 x[2][2]=9

Row Col inside a row

23

Page 24: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Multidimensional Arrays

• Multidimensional arrays stand for the arrays with two or more dimensions.

• Syntax for normal usage: element-type aname[size1][size2]…[sizen]; Syntax for parameter in function prototype: element-type aname[][size2]…[sizen]

• e.g., char tictac[3][3];

– A 2-dimensional array with three rows and three columns.

• e.g., tictac[][3];

– The declaration for the function prototype. 24

Page 25: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

The Memory Allocated for tictac[3][3]

• The memory allocated for array

tictac[3][3]is shown below.

• The number of total allocated element is

3*3=9 elements.

25

Page 26: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Initialization of Multidimensional

Arrays • The multidimensional array can also be

initialized in declarations.

• The initialized values are grouped in rows.

– e.g., char tictac[3][3]={{‘a’, ’b’, ’c’}, {‘d’, ’e’, ’f’}, {‘ ’,‘ ’,‘

’}};

• We can also declare arrays with more dimensions.

– e.g., declare a 3-dimensional array. int

enroll[course][campus][cls_rank]; 26

Page 27: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

2D array in address space(1)

• How to store a multi-

dimensional array into a one-

dimensional memory space.

• Row major ordering assigns

successive elements, moving

across the rows and then down

the columns, to successive

memory locations.

Base_Address is the address of the first element of the array (A[0][0] in this case).

char *base = &A[0][0];

Referring A[i][j] is same as referring *(base+4*i+j); //4 is column here

27

Page 28: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

2D array in address space(2)

int a[2][3]; // 2 rows and 3 cols

• Alternative interpretation: Three 1D array of 4 integers.

• The base address of the array is &a[0][0].

• The array name a by itself is equivalent to &a[0]. This time it is

a pointer to an array of 3 elements.

• Different ways to access (i,j) th element:

a[i][j]

*(a[i] + j)

*((*(a+i)) + j)

*(&a[0][0] + 3*i + j)

a[1][2]

a[1][1]

a[1][0]

a[0][2]

a[0][1]

a[0][0] a

a+1

28

Page 29: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Multi-dimensional Arrays.

Declaration int a[N]; int b[M][N]; int c[L][M][N];

Array element a[i] b[i][j] c[i][j][k]

Pointer to element a b[i] c[i][j]

Pointer to 1D array of N element

b c[i]

Pointer to 2D array of M*N element

c

29

Page 30: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Passing Multidimensional array

arr[7][9][2] = {0}; … sum(arr,7); … int sum(int a[][9][2], int asize){ int i, j, k, sum = 0 for( i = 0; i<asize; ++i) { for( j = 0; j<9; ++j) { for( k = 0; k<2; ++k) { sum += a[i][j][k]; return sum; }

For a multidimensional array

we must declare all but the first

dimension. Only 7 can be

omitted.

30

Page 31: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

The Memory Allocated for enroll[100][5][4]

enroll[100][5][4]

consists of 100*5*4

=2000 elements.

31

Page 32: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Figure 8.9 Function to Add Two Arrays

32

Page 33: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Figure 8.10 Function Data Areas for

add_arrays(x, y, x_plus_y, 5);

33

Page 34: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Partially Filled Arrays

• Frequently, a program will need to process many lists of similar data

• These list may not all be the same length

• In order to reuse an array for processing more than one data set, the programmer often declares an array large enough to hold the largest data set anticipated.

• This array can be used for processing shorter lists as well, provided that the program keeps track of how many array elements are actually in use.

• One way to do this is to have the original array size declared as the highest needed, and then store a sentinel value after the last value inputted.

34

Page 35: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Sorting an Array – Selection Sort

• Similar to sorting cards.

35

Page 36: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Figure 8.16 Trace of Selection Sort Not included

36

Page 37: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 37

Page 38: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Common Programming Errors

• The most common error in using arrays is a subscript-range error.

• An out-of-range reference occurs when the subscript value is outside the range specified by the array declaration. – In some situations, no run-time error message will be

produced – the program will simply produce incorrect results.

– Other times, you may get a runtime error like “segmentation fault” or “bus error”

• Remember how to pass arrays to functions.

• Remember that the first index of the array is 0

38

Page 39: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Study (1)

• Write a function that computes the average grades and

sorts the grades of two classes.

• Your program should input two lists of grades for each

class.

• Your program should output:

(1) average grades for each class;

(2) a list of sorted grades of two classes.

• You can use the sorting function in p.401 in the text

book.

• You can either assume the number of students in each

class is fixed or prompt the user to input the number. 39

Page 40: BİL 133 – Algoritma ve Programlama Chapter 8: Arrays and ... · Searching and Sorting an Array •Sometimes we may need to –search a particular value in an array, or –sort

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

Study (2)

• e.g.,

Please input grades of 1st class:

55 45 65 85 75

Please input grades of 2nd class:

80 70 50 60 40

Output:

The average grades of 1st class is: 65

The average grades of 2nd class is: 60

The sorted grades of two classes are:

40 45 50 55 60 65 70 75 80 85 40