Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Pointers and Arrays Chapter 12
Programming and Data Structure
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 Pearson Education, Inc. All rights reserved Arrays.
C programming---Arrays scalar: capable of holding a single data item aggregate variables: capable of holding a collections of values. Two kinds of aggregates.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Lists in Python.
 2006 Pearson Education, Inc. All rights reserved Arrays.
A First Book of ANSI C Fourth Edition
Computer programming Lecture 5. Lecture 5: Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character arrays.
Chapter 8 Arrays and Strings
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 11 introduced pointers and showed how they're used as function arguments and as values returned by functions. This chapter covers another application.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Chapter 11: Pointers Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 11 Pointers.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
COP 3275: Chapter 08 Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA.
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Sorting –Bubble sort –Merge sort –Quick sort –Selection.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
C programming---Pointers The first step: visualizing what pointers represent at the machine level. In most modern computers, main memory is divided into.
Chapter 8: Arrays Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Move the first element to the.
8. ARRAYS. Aggregate variables Scalar variables –Single value Aggregate variables –Collection of values –Arrays: elements have the same type.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Gator Engineering Google Code Jam 2015 Copyright © 2008 W. W. Norton & Company. All rights reserved. 1.
Chapter 12: Pointers and Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
EGR 2261 Unit 10 Two-dimensional Arrays
© 2016 Pearson Education, Ltd. All rights reserved.
C programming---Arrays
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Pointers and Arrays Chapter 12
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company. 1
Expressions Chapter 4 Copyright © 2008 W. W. Norton & Company.
7 Arrays.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
Pointers and Arrays Chapter 12
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Pointers (continued) Chapter 11
Regrading Project 2 Exam 2 One week period TA: Huiyuan TA: Fardad
Pointers and Arrays Chapter 12
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Strings Chapter 13 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
7 Arrays.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Presentation transcript:

Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays

Scalar Variables versus Aggregate Variables So far, the only variables we’ve seen are scalar: capable of holding a single data item. C also supports aggregate variables, which can store collections of values. There are two kinds of aggregates in C: arrays and structures. The focus of the chapter is on one-dimensional arrays, which play a much bigger role in C than do multidimensional arrays. Copyright © 2008 W. W. Norton & Company. All rights reserved. 2

One-Dimensional Arrays An array is a data structure containing a number of data values, all of which have the same type. These values, known as elements, can be individually selected by their position within the array. The simplest kind of array has just one dimension. The elements of a one-dimensional array a are conceptually arranged one after another in a single row (or column): Copyright © 2008 W. W. Norton & Company. All rights reserved. 3

One-Dimensional Arrays To declare an array, we must specify the type of the array’s elements and the number of elements: int a[10]; The elements may be of any type; the length of the array can be any (integer) constant expression. Using a macro to define the length of an array is an excellent practice: #define N 10 … int a[N]; Copyright © 2008 W. W. Norton & Company. All rights reserved. 4

Array Subscripting To access an array element, write the array name followed by an integer value in square brackets. This is referred to as subscripting or indexing the array. The elements of an array of length n are indexed from 0 to n – 1. If a is an array of length 10, its elements are designated by a[0], a[1], …, a[9] : Copyright © 2008 W. W. Norton & Company. All rights reserved. 5

Array Subscripting Expressions of the form a[i] are lvalues, so they can be used in the same way as ordinary variables: a[0] = 1; printf("%d\n", a[5]); ++a[i]; In general, if an array contains elements of type T, then each element of the array is treated as if it were a variable of type T. Copyright © 2008 W. W. Norton & Company. All rights reserved. 6

Array Subscripting Many programs contain for loops whose job is to perform some operation on every element in an array. Examples of typical operations on an array a of length N : for (i = 0; i < N; i++) a[i] = 0; /* clears a */ for (i = 0; i < N; i++) scanf("%d", &a[i]); /* reads data into a */ for (i = 0; i < N; i++) sum += a[i]; /* sums the elements of a */ Copyright © 2008 W. W. Norton & Company. All rights reserved. 7

Array Subscripting C doesn’t require that subscript bounds be checked; if a subscript goes out of range, the program’s behavior is undefined. A common mistake: forgetting that an array with n elements is indexed from 0 to n – 1, not 1 to n: int a[10], i; for (i = 1; i <= 10; i++) a[i] = 0; With some compilers, this innocent-looking for statement causes an infinite loop. Copyright © 2008 W. W. Norton & Company. All rights reserved. 8

Array Subscripting An array subscript may be any integer expression: a[i+j*10] = 0; The expression can even have side effects: i = 0; while (i < N) a[i++] = 0; Copyright © 2008 W. W. Norton & Company. All rights reserved. 9

Array Subscripting Be careful when an array subscript has a side effect: i = 0; while (i < N) a[i] = b[i++]; The expression a[i] = b[i++] accesses the value of i and also modifies i, causing undefined behavior. The problem can be avoided by removing the increment from the subscript: for (i = 0; i < N; i++) a[i] = b[i]; Copyright © 2008 W. W. Norton & Company. All rights reserved. 10

Program: Reversing a Series of Numbers The reverse.c program prompts the user to enter a series of numbers, then writes the numbers in reverse order: Enter 10 numbers: In reverse order: The program stores the numbers in an array as they’re read, then goes through the array backwards, printing the elements one by one. Copyright © 2008 W. W. Norton & Company. All rights reserved. 11

reverse.c /* Reverses a series of numbers */ #include #define N 10 int main(void) { int a[N], i; printf("Enter %d numbers: ", N); for (i = 0; i < N; i++) scanf("%d", &a[i]); printf("In reverse order:"); for (i = N - 1; i >= 0; i--) printf(" %d", a[i]); printf("\n"); return 0; } Copyright © 2008 W. W. Norton & Company. All rights reserved. 12

Array Initialization An array, like any other variable, can be given an initial value at the time it’s declared. The most common form of array initializer is a list of constant expressions enclosed in braces and separated by commas: int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Copyright © 2008 W. W. Norton & Company. All rights reserved. 13

Array Initialization If the initializer is shorter than the array, the remaining elements of the array are given the value 0: int a[10] = {1, 2, 3, 4, 5, 6}; /* initial value of a is {1, 2, 3, 4, 5, 6, 0, 0, 0, 0} */ Using this feature, we can easily initialize an array to all zeros: int a[10] = {0}; /* initial value of a is {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */ There’s a single 0 inside the braces because it’s illegal for an initializer to be completely empty. It’s also illegal for an initializer to be longer than the array it initializes. Copyright © 2008 W. W. Norton & Company. All rights reserved. 14

Array Initialization If an initializer is present, the length of the array may be omitted: int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; The compiler uses the length of the initializer to determine how long the array is. Copyright © 2008 W. W. Norton & Company. All rights reserved. 15

Using the sizeof Operator with Arrays The sizeof operator can determine the size of an array (in bytes). If a is an array of 10 integers, then sizeof(a) is typically 40 (assuming that each integer requires four bytes). We can also use sizeof to measure the size of an array element, such as a[0]. Dividing the array size by the element size gives the length of the array: sizeof(a) / sizeof(a[0]) Copyright © 2008 W. W. Norton & Company. All rights reserved. 16

Using the sizeof Operator with Arrays Some programmers use this expression when the length of the array is needed. A loop that clears the array a : for (i = 0; i < sizeof(a) / sizeof(a[0]); i++) a[i] = 0; Note that the loop doesn’t have to be modified if the array length should change at a later date. Copyright © 2008 W. W. Norton & Company. All rights reserved. 17

Multidimensional Arrays An array may have any number of dimensions. The following declaration creates a two-dimensional array (a matrix, in mathematical terminology): int m[5][9]; m has 5 rows and 9 columns. Both rows and columns are indexed from 0: Copyright © 2008 W. W. Norton & Company. All rights reserved. 18

Multidimensional Arrays To access the element of m in row i, column j, we must write m[i][j]. The expression m[i] designates row i of m, and m[i][j] then selects element j in this row. Resist the temptation to write m[i,j] instead of m[i][j]. C treats the comma as an operator in this context, so m[i,j] is the same as m[j]. Copyright © 2008 W. W. Norton & Company. All rights reserved. 19

Multidimensional Arrays Although we visualize two-dimensional arrays as tables, that’s not the way they’re actually stored in computer memory. C stores arrays in row-major order, with row 0 first, then row 1, and so forth. How the m array is stored: Copyright © 2008 W. W. Norton & Company. All rights reserved. 20

Multidimensional Arrays Nested for loops are ideal for processing multidimensional arrays. Consider the problem of initializing an array for use as an identity matrix. A pair of nested for loops is perfect: #define N 10 double ident[N][N]; int row, col; for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (row == col) ident[row][col] = 1.0; else ident[row][col] = 0.0; Copyright © 2008 W. W. Norton & Company. All rights reserved. 21

Initializing a Multidimensional Array We can create an initializer for a two-dimensional array by nesting one-dimensional initializers: int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 1, 0, 0, 1, 0}, {1, 1, 0, 1, 0, 0, 0, 1, 0}, {1, 1, 0, 1, 0, 0, 1, 1, 1}}; Initializers for higher-dimensional arrays are constructed in a similar fashion. C provides a variety of ways to abbreviate initializers for multidimensional arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 22

Initializing a Multidimensional Array If an initializer isn’t large enough to fill a multidimensional array, the remaining elements are given the value 0. The following initializer fills only the first three rows of m ; the last two rows will contain zeros: int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 1, 0, 0, 1, 0}}; Copyright © 2008 W. W. Norton & Company. All rights reserved. 23

Initializing a Multidimensional Array If an inner list isn’t long enough to fill a row, the remaining elements in the row are initialized to 0: int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1}, {0, 1, 0, 1, 1, 0, 0, 1}, {1, 1, 0, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 0, 1, 1, 1}}; Copyright © 2008 W. W. Norton & Company. All rights reserved. 24

Initializing a Multidimensional Array We can even omit the inner braces: int m[5][9] = {1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1}; Once the compiler has seen enough values to fill one row, it begins filling the next. Omitting the inner braces can be risky, since an extra element (or even worse, a missing element) will affect the rest of the initializer. Copyright © 2008 W. W. Norton & Company. All rights reserved. 25

Constant Arrays An array can be made “constant” by starting its declaration with the word const : const char hex_chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; An array that’s been declared const should not be modified by the program. Copyright © 2008 W. W. Norton & Company. All rights reserved. 26

Constant Arrays Advantages of declaring an array to be const : –Documents that the program won’t change the array. –Helps the compiler catch errors. const isn’t limited to arrays, but it’s particularly useful in array declarations. Copyright © 2008 W. W. Norton & Company. All rights reserved. 27

Program: Dealing a Hand of Cards The deal.c program illustrates both two- dimensional arrays and constant arrays. The program deals a random hand from a standard deck of playing cards. Each card in a standard deck has a suit (clubs, diamonds, hearts, or spades) and a rank (two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, or ace). Copyright © 2008 W. W. Norton & Company. All rights reserved. 28

Program: Dealing a Hand of Cards The user will specify how many cards should be in the hand: Enter number of cards in hand: 5 Your hand: 7c 2s 5d as 2h Problems to be solved: –How do we pick cards randomly from the deck? –How do we avoid picking the same card twice? Copyright © 2008 W. W. Norton & Company. All rights reserved. 29

Program: Dealing a Hand of Cards To pick cards randomly, we’ll use several C library functions: –time (from ) – returns the current time, encoded in a single number. –srand (from ) – initializes C’s random number generator. –rand (from ) – produces an apparently random number each time it’s called. By using the % operator, we can scale the return value from rand so that it falls between 0 and 3 (for suits) or between 0 and 12 (for ranks). Copyright © 2008 W. W. Norton & Company. All rights reserved. 30

Program: Dealing a Hand of Cards The in_hand array is used to keep track of which cards have already been chosen. The array has 4 rows and 13 columns; each element corresponds to one of the 52 cards in the deck. All elements of the array will be false to start with. Each time we pick a card at random, we’ll check whether the element of in_hand corresponding to that card is true or false. –If it’s true, we’ll have to pick another card. –If it’s false, we’ll store true in that element to remind us later that this card has already been picked. Copyright © 2008 W. W. Norton & Company. All rights reserved. 31

Program: Dealing a Hand of Cards Once we’ve verified that a card is “new,” we’ll need to translate its numerical rank and suit into characters and then display the card. To translate the rank and suit to character form, we’ll set up two arrays of characters—one for the rank and one for the suit—and then use the numbers to subscript the arrays. These arrays won’t change during program execution, so they are declared to be const. Copyright © 2008 W. W. Norton & Company. All rights reserved. 32

deal.c /* Deals a random hand of cards */ #include /* C99 only */ #include #define NUM_SUITS 4 #define NUM_RANKS 13 int main(void) { bool in_hand[NUM_SUITS][NUM_RANKS] = {false}; int num_cards, rank, suit; const char rank_code[] = {'2','3','4','5','6','7','8', '9','t','j','q','k','a'}; const char suit_code[] = {'c','d','h','s'}; Copyright © 2008 W. W. Norton & Company. All rights reserved. 33

srand((unsigned) time(NULL)); printf("Enter number of cards in hand: "); scanf("%d", &num_cards); printf("Your hand:"); while (num_cards > 0) { suit = rand() % NUM_SUITS; /* picks a random suit */ rank = rand() % NUM_RANKS; /* picks a random rank */ if (!in_hand[suit][rank]) { in_hand[suit][rank] = true; num_cards--; printf(" %c%c", rank_code[rank], suit_code[suit]); } printf("\n"); return 0; } Copyright © 2008 W. W. Norton & Company. All rights reserved. 34

Copyright © 2008 W. W. Norton & Company. All rights reserved. 35 Chapter 11 Pointers

Pointer Variables The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable of storing eight bits of information: Each byte has a unique address. Copyright © 2008 W. W. Norton & Company. All rights reserved. 36

Pointer Variables If there are n bytes in memory, we can think of addresses as numbers that range from 0 to n – 1: Copyright © 2008 W. W. Norton & Company. All rights reserved. 37

Pointer Variables Each variable in a program occupies one or more bytes of memory. The address of the first byte is said to be the address of the variable. In the following figure, the address of the variable i is 2000: Copyright © 2008 W. W. Norton & Company. All rights reserved. 38

Pointer Variables Addresses can be stored in special pointer variables. When we store the address of a variable i in the pointer variable p, we say that p “points to” i. A graphical representation: Copyright © 2008 W. W. Norton & Company. All rights reserved. 39

Declaring Pointer Variables When a pointer variable is declared, its name must be preceded by an asterisk: int *p; p is a pointer variable capable of pointing to objects of type int. We use the term object instead of variable since p might point to an area of memory that doesn’t belong to a variable. Copyright © 2008 W. W. Norton & Company. All rights reserved. 40

Declaring Pointer Variables Pointer variables can appear in declarations along with other variables: int i, j, a[10], b[20], *p, *q; C requires that every pointer variable point only to objects of a particular type (the referenced type): int *p; /* points only to integers */ double *q; /* points only to doubles */ char *r; /* points only to characters */ There are no restrictions on what the referenced type may be. Copyright © 2008 W. W. Norton & Company. All rights reserved. 41

The Address and Indirection Operators C provides a pair of operators designed specifically for use with pointers. –To find the address of a variable, we use the & (address) operator. –To gain access to the object that a pointer points to, we use the * (indirection) operator. Copyright © 2008 W. W. Norton & Company. All rights reserved. 42

The Address Operator Declaring a pointer variable sets aside space for a pointer but doesn’t make it point to an object: int *p; /* points nowhere in particular */ It’s crucial to initialize p before we use it. Copyright © 2008 W. W. Norton & Company. All rights reserved. 43

The Address Operator One way to initialize a pointer variable is to assign it the address of a variable: int i, *p; … p = &i; Assigning the address of i to the variable p makes p point to i : Copyright © 2008 W. W. Norton & Company. All rights reserved. 44

The Address Operator It’s also possible to initialize a pointer variable at the time it’s declared: int i; int *p = &i; The declaration of i can even be combined with the declaration of p : int i, *p = &i; Copyright © 2008 W. W. Norton & Company. All rights reserved. 45

The Indirection Operator Once a pointer variable points to an object, we can use the * (indirection) operator to access what’s stored in the object. If p points to i, we can print the value of i as follows: printf("%d\n", *p); Applying & to a variable produces a pointer to the variable. Applying * to the pointer takes us back to the original variable: j = *&i; /* same as j = i; */ Copyright © 2008 W. W. Norton & Company. All rights reserved. 46

The Indirection Operator As long as p points to i, *p is an alias for i. –*p has the same value as i. –Changing the value of *p changes the value of i. The example on the next slide illustrates the equivalence of *p and i. Copyright © 2008 W. W. Norton & Company. All rights reserved. 47

The Indirection Operator p = &i; i = 1; printf("%d\n", i); /* prints 1 */ printf("%d\n", *p); /* prints 1 */ *p = 2; printf("%d\n", i); /* prints 2 */ printf("%d\n", *p); /* prints 2 */ Copyright © 2008 W. W. Norton & Company. All rights reserved. 48

The Indirection Operator Applying the indirection operator to an uninitialized pointer variable causes undefined behavior: int *p; printf("%d", *p); /*** WRONG ***/ Assigning a value to *p is particularly dangerous: int *p; *p = 1; /*** WRONG ***/ Copyright © 2008 W. W. Norton & Company. All rights reserved. 49

Pointer Assignment C allows the use of the assignment operator to copy pointers of the same type. Assume that the following declaration is in effect: int i, j, *p, *q; Example of pointer assignment: p = &i; Copyright © 2008 W. W. Norton & Company. All rights reserved. 50

Pointer Assignment Another example of pointer assignment: q = p; q now points to the same place as p : Copyright © 2008 W. W. Norton & Company. All rights reserved. 51

Pointer Assignment If p and q both point to i, we can change i by assigning a new value to either *p or *q : *p = 1; *q = 2; Any number of pointer variables may point to the same object. Copyright © 2008 W. W. Norton & Company. All rights reserved. 52

Pointer Assignment Be careful not to confuse q = p; with *q = *p; The first statement is a pointer assignment, but the second is not. The example on the next slide shows the effect of the second statement. Copyright © 2008 W. W. Norton & Company. All rights reserved. 53

Pointer Assignment p = &i; q = &j; i = 1; *q = *p; Copyright © 2008 W. W. Norton & Company. All rights reserved. 54

Pointers as Arguments In Chapter 9, we tried—and failed—to write a decompose function that could modify its arguments. By passing a pointer to a variable instead of the value of the variable, decompose can be fixed. Copyright © 2008 W. W. Norton & Company. All rights reserved. 55

Pointers as Arguments New definition of decompose : void decompose(double x, long *int_part, double *frac_part) { *int_part = (long) x; *frac_part = x - *int_part; } Possible prototypes for decompose : void decompose(double x, long *int_part, double *frac_part); void decompose(double, long *, double *); Copyright © 2008 W. W. Norton & Company. All rights reserved. 56

Pointers as Arguments A call of decompose : decompose( , &i, &d); As a result of the call, int_part points to i and frac_part points to d : Copyright © 2008 W. W. Norton & Company. All rights reserved. 57

Pointers as Arguments The first assignment in the body of decompose converts the value of x to type long and stores it in the object pointed to by int_part : Copyright © 2008 W. W. Norton & Company. All rights reserved. 58

Pointers as Arguments The second assignment stores x - *int_part into the object that frac_part points to: Copyright © 2008 W. W. Norton & Company. All rights reserved. 59

Pointers as Arguments Arguments in calls of scanf are pointers: int i; … scanf("%d", &i); Without the &, scanf would be supplied with the value of i. Copyright © 2008 W. W. Norton & Company. All rights reserved. 60

Pointers as Arguments Although scanf ’s arguments must be pointers, it’s not always true that every argument needs the & operator: int i, *p; … p = &i; scanf("%d", p); Using the & operator in the call would be wrong: scanf("%d", &p); /*** WRONG ***/ Copyright © 2008 W. W. Norton & Company. All rights reserved. 61

Pointers as Arguments Failing to pass a pointer to a function when one is expected can have disastrous results. A call of decompose in which the & operator is missing: decompose( , i, d); When decompose stores values in *int_part and *frac_part, it will attempt to change unknown memory locations instead of modifying i and d. If we’ve provided a prototype for decompose, the compiler will detect the error. In the case of scanf, however, failing to pass pointers may go undetected. Copyright © 2008 W. W. Norton & Company. All rights reserved. 62

Program: Finding the Largest and Smallest Elements in an Array The max_min.c program uses a function named max_min to find the largest and smallest elements in an array. Prototype for max_min : void max_min(int a[], int n, int *max, int *min); Example call of max_min : max_min(b, N, &big, &small); When max_min finds the largest element in b, it stores the value in big by assigning it to *max. max_min stores the smallest element of b in small by assigning it to *min. Copyright © 2008 W. W. Norton & Company. All rights reserved. 63

Program: Finding the Largest and Smallest Elements in an Array max_min.c will read 10 numbers into an array, pass it to the max_min function, and print the results: Enter 10 numbers: Largest: 102 Smallest: 7 Copyright © 2008 W. W. Norton & Company. All rights reserved. 64

maxmin.c /* Finds the largest and smallest elements in an array */ #include #define N 10 void max_min(int a[], int n, int *max, int *min); int main(void) { int b[N], i, big, small; printf("Enter %d numbers: ", N); for (i = 0; i < N; i++) scanf("%d", &b[i]); Copyright © 2008 W. W. Norton & Company. All rights reserved. 65

max_min(b, N, &big, &small); printf("Largest: %d\n", big); printf("Smallest: %d\n", small); return 0; } void max_min(int a[], int n, int *max, int *min) { int i; *max = *min = a[0]; for (i = 1; i < n; i++) { if (a[i] > *max) *max = a[i]; else if (a[i] < *min) *min = a[i]; } Copyright © 2008 W. W. Norton & Company. All rights reserved. 66

Using const to Protect Arguments When an argument is a pointer to a variable x, we normally assume that x will be modified: f(&x); It’s possible, though, that f merely needs to examine the value of x, not change it. The reason for the pointer might be efficiency: passing the value of a variable can waste time and space if the variable requires a large amount of storage. Copyright © 2008 W. W. Norton & Company. All rights reserved. 67

Using const to Protect Arguments We can use const to document that a function won’t change an object whose address is passed to the function. const goes in the parameter’s declaration, just before the specification of its type: void f(const int *p) { *p = 0; /*** WRONG ***/ } Attempting to modify *p is an error that the compiler will detect. Copyright © 2008 W. W. Norton & Company. All rights reserved. 68

Pointers as Return Values Functions are allowed to return pointers: int *max(int *a, int *b) { if (*a > *b) return a; else return b; } A call of the max function: int *p, i, j; … p = max(&i, &j); After the call, p points to either i or j. Copyright © 2008 W. W. Norton & Company. All rights reserved. 69

Pointers as Return Values Although max returns one of the pointers passed to it as an argument, that’s not the only possibility. A function could also return a pointer to an external variable or to a static local variable. Never return a pointer to an automatic local variable: int *f(void) { int i; … return &i; } The variable i won’t exist after f returns. Copyright © 2008 W. W. Norton & Company. All rights reserved. 70

Pointers as Return Values Pointers can point to array elements. If a is an array, then &a[i] is a pointer to element i of a. It’s sometimes useful for a function to return a pointer to one of the elements in an array. A function that returns a pointer to the middle element of a, assuming that a has n elements: int *find_middle(int a[], int n) { return &a[n/2]; } Copyright © 2008 W. W. Norton & Company. All rights reserved. 71