Applications of pointers II: References,
Indirection
(ポインタの応用 I: 参照、間接)
Computing Practice I
11th lecture, June 29, 2017
http://www.sw.it.aoyama.ac.jp/2017/CP1/lecture11.html
Martin J. Dürst
© 2005-17 Martin
J. Dürst 青山学院大学
Today's Schedule
- Minitest
- Summary of last lecture
- Call by reference
- Indirection
- Functions as arguments
- Today's exercises
ミニテスト
- 授業開始までにログイン済み
- ナビゲーションは左に畳み、ブラウザは全画面に拡大
- 授業開始まで教科書、資料、筆箱、財布などを鞄に入れ、鞄を椅子の下に
- テスト終了後その場で待つ
Summary of Last Lecture
- Variables are placed on the stack, on the heap,... depending on their
kind (global, local,...)
- Array index calculations can be converted to pointer calculations
- Dynamic memory is allocated with
malloc
, resized with
realloc
, and returned with free
- Use patterns for dynamic memory handling, and make sure it is clear who
is responsibly for freeing the memory
Results of Previous Exercises
|
10A1 |
10B2 |
10C1 |
10C2 |
100 points |
97 |
50 |
32 |
4 |
60 points |
1 |
48 |
62 |
32 |
partial |
1 |
48 |
62 |
17 |
errors |
- |
- |
3 |
34 |
not submitted |
1 |
1 |
2 |
13 |
10C2 の注意点
- ダメもとで前のプログラムを出すことは「挑戦」とは言えません
- もっと Q&A フォーラムを使うべき!
- 読み込み済み文字の数と用意されたメモリの長さ
- 行頭の
EOF
: NULL
を返却
- 行中の改行: 改行を保持、
\0
を追加
- 行中の
EOF
: 読み込みを終了、\0
を追加
Usages of Pointers
- Low-level address manipulation (device allocation,...)
- Speedup of array processing
- Dynamic memory management
- Reference (passing of arguments to a function by reference,...)
- Indirection
References in Natural Language
- He, she, they
- This, that
- Here, there
- Names or words for things
- ...
引数の値渡しと参照渡しのイメージ
値渡し (call by value):
- 付箋に値を書いて、捨ててもいいように渡す
- 修理するものを直接渡す (例: 靴の修理)
参照渡し (call by reference):
- 箱の中に値を用意し、箱の場所を渡す
- 修理する場所 (住所) を指定 (例: 水道管の修理)
Call by Reference
- 目的:
- 関数に値を渡すのではなく、
- 変数への参照を渡すことで
- 変数そのものが関数から変更可能
- 技法:
- 引数をポインタとして定義
- 関数呼び出し時にアドレス演算子 (
&
)
を使用
- 関数の中には常に間接演算子 (
*
)
を使用
- 問題点:
- 自動ではないので注意
(特に scanf
などコンパイル時に型のチェックが不可能な場合)
Pattern for Call by Reference (Except Arrays)
Pattern for Call by Reference (Arrays)
- Because arrays and pointers are (almost) the same, call by reference is
automatic
- On the callee side, pointers and arrays are equivalent
(for an argument definition, e.g. int *a;
and int
a[];
are identical)
- Caution: How to know the length of the array:
- Special value to signal the end of the array (e.g.:
'\0'
for strings, exercise 11C1)
- Pass the length as a separate argument (e.g. second argument of
qsort
)
How to Pass Arrays by Value
- Call by reference, do not change in callee
- As in (1), but add
const
qualifiers to declare and assure
there are no changes
- Copy data before passing it
- Wrap the array in a
struct
, and pass the struct
(which is passed by value)
Application of Call by Reference: Multiple Return Values
Problem: Create a function that returns both n2 and
n3
Solution: Pass uninitialized variables by reference:
void square_cube(int n, int *pn2, int *pn3)
{
*pn2 = n * n;
*pn3 = *pn2 * n;
}
Caller side:
int a=5, a2, a3;
square_cube(a, &a2, &a3);
printf("a=%d, a*a=%d, a*a*a=%d\n", a, a2, a3);
Indirection
名言:
「全ての情報テクノロジーの問題は間接のレベルを一つ増やせば解決可能」
間接の例:
- IP アドレスの代わりにドメイン名
- 学生本人の代わりにあだ名、学生番号、メールアドレス
- データベースのインデックス
- Web ページ本体とそのアドレス (http://... など)
- Google, Yahoo みたいなサーチエンジン
C の場合には間接をポインタで実現
Applications of Indirection
順番を入れ替える時に、実際のデータを入れ替えると:
- データの移動が大変
- データの場所が変更、他のところで困る
- 同時に一つの順番しか使えない
間接を使えば全ての問題が解決 (例: 11C2)
Functions as Arguments
(pointers to) functions can be passed as arguments to other functions
Typical example: Execute some 'work' according to some pattern, where the
'work' details are not fixed
Application example: Execute some work (e.g. clean blackbords, clean room,
switch off lights, check air quality, check fire alarms...) in all lecture
halls of Sagamihara campus
Solution:
- Create a "lecture hall tracer" function
- Pass the function doing the actual work to the "lecture hall tracer"
function
- The "lecture hall tracer" function calls the "actual work" function in
every lecture hall
How to Implement Sorting
- There are many criteria for sorting
(student number, name, grades, increasing/decreasing)
- There are many different methods for sorting
(bubble sort, insertion sort,...; we will study them in the course Data
Structures and Algorithms in the fall term)
- To cover everything, we need many complicated functions
|
bubble sort |
insertion sort |
selection sort |
quicksort |
... |
Student number |
|
|
|
|
|
Name |
|
|
|
|
|
Math grades |
|
|
|
|
|
English grades |
|
|
|
|
|
... |
|
|
|
|
|
Introducing Comparison Functions
- The sort criterion and the sorting method are independent of each
other
- The order of data items can be expressed by a comparison
function
- The comparison function compares two items a and b,
and returns:
- A negative number if a comes earlier
- A positive number if b comes earlier
- Zero if a and b are the same
- If we can pass the comparison function to the sorting function:
- We need only one sorting function (provided by a library, e.g.
qsort
)
- The comparison function can be quite simple
Functions as Arguments in Other Programming Languages
- The C programming language requires some effort to create a function
- The comparison function needs to work with all kinds of data, and
therefore uses pointers
- There are programming languages where creating functions is much
easier:
Functional languages (Lisp, Haskell,...)
- In Ruby, many methods (member
functions) use blocks (similar to functions) as arguments
Example of Difference between Languages
Ruby: students.sort { |a, b| a.number <=> b.number }
Or even easier: students.sort_by { |a| a.number }
Shorthand: students.sort_by &:number
C (from 11C2):
int compareNumbers (const void* a, const void* b)
{
Student *studentPa = *((Student **) a);
Student *studentPb = *((Student **) b);
return strcmp (studentPa->studentNumber,
studentPb->studentNumber);
}
...
qsort(byNumber, studentCount, sizeof(Student*), compareNumbers);
今日の演習
- 11A1: 参照渡しの基本
- 11C1: 参照渡しを使って値を帰す
- 11C2: 全置き換えの作成
- 11C3: 学生データの整列
- 全点必須
(発展問題ではない)
- 順番を追加するごとに提出 (部分点)
- 帰宅前に必ず2点以上取得
- 締切は月曜日
穴埋めや追加が多いので、インデントに注意
次回の準備
- 残りの演習問題を宿題として完成
- 今日の復習
- 参考書の第 11 章 (pp. 281-311) をもう一回よく読む
- 参考書の第 12 章 (ファイル操作、pp. 313-345) を読む
Glossary
- call (pass) by reference
- 参照渡し
- array index
- 配列の指数
- callee side
- (呼ばれた) 関数側
- caller side
- 呼び出し側
- sort(ing)
- ソート、整列
- (sort) criterion
- (整列の) 基準
- bubble sort
- バブル整列
- insertion sort
- 挿入整列
- selection sort
- 選択整列
- quicksort
- クイックソート
- comparison function
- 比較関数