Applications of Pointers II: References,
Indirection
(ポインタの応用 I: 参照、間接)
Computing Practice I
11th lecture, June 21, 2018
http://www.sw.it.aoyama.ac.jp/2018/CP1/lecture11.html
Martin J. Dürst
© 2005-18 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 |
95 |
56 |
28 |
- |
60 points |
4 |
43 |
61 |
9 |
partial |
- |
- |
- |
12 |
errors |
1 |
1 |
10 |
53 |
not submitted |
- |
- |
|
26 |
Main Points for Problem 10C2
- Ask more questions on the Q&A Forum!
- Relationship between number of characters read and size of memory
EOF
at start of line: return NULL
- Line break: Stop reading, save line break character, add
\0
EOF
in the middle of a line: Stop reading, add
\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
- ...
Examples of Call by Value and Call by Reference
Call by value:
- Directly pass the thing to be fixed (Ex: Shoe repair)
- Write value on a piece of paper, pass the paper (can be thrown away)
Call by reference:
- Indicate the address of the thing to be fixed (Ex: Water pipe repair)
- Put value in a box, pass the address of the box
Call by Reference
- Goal:
Not to pass a value to the function,
but to pass a reference to a variable,
so that the variable can be changed from the function
- Technique:
- Define function argument as a pointer
- When calling the function, use the address operator
(
&
)
- Inside the function, always use the dereference operator
(
*
)
- Problem:
- Caution, this is not automatic
(especially for functions such as scanf
where the argument
types are not checked at compile time)
Pattern for Call by Reference (Except Arrays)
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);
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)
Calling Conventions Overview
|
everything except arrays |
arrays |
call by value |
automatic |
copy before calling, wrap in struct, use const |
call by reference |
use pointers |
automatic (except length) |
Indirection
Famous quote:
"All problems in computer science can be solved by another level of
indirection"
Examples of indirection:
- Using domain names instead of IP addresses:
Direct: IP address → computer
Indirect: domain name → IP address → computer
- Use name, student number, or mail address as a replacement for a
student
- Index in a database:
Actual data in order of insertion
Index used for access e.g. by student number, by family name, by given
name
- Web page vs. its address (http://... and so on)
- Search engines such as Google, Bing, Yahoo,...
In C, indirection is realized using pointers
Applications of Indirection
When ordering data, actually moving the data around means:
- Moving around big amounts of data takes time
(when you reorder files in a file explorer, the actual data doesn't get
moved around)
- When data is moving, other references to it become invalid
- Data can only be kept in one single order
Indirection can solve all these problems (e.g. 11C3)
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 the 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 11C3):
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
- 比較関数