Title: Pointer (III)
1Pointer (III)
- CGS 3460, Lecture 30
- Mar 27, 2006
- Hen-I Yang
2Previously
- Address and Indirection Operators.
- Use of Pointers.
3Quiz 4
- On May 31, Friday, at the beginning of the class
- 20 Minutes, 3 Questions
- Covers
- Homework 4
- Textbook Chapter 7 10,
- Slides up to Lecture 26 (May 10)
- All rules from previous quizzes apply (Gator 1
ID, no electronic devices, etc)
4Agenda
- Use of Pointers.
- Array and Pointers
5Why do we use pointers?
- Pass as argument or Return the value
- Dynamic variables
- More efficient
- Refer to part of the a larger variable
6Use of Pointers as argument
- Pointer as argument
- So the function can modify the value of the
argument passed - C functions are Pass by Value
- scanf(d, i)
- Const modifier
7Use of Pointers as return value
- Use pointer as return value
- int max (int a, int b)
- if (a gt b)
- return a
- else
- return b
-
- int p, x, y
- p max (x, y)
- Do not return local variable or local pointer
variable when return type is a pointer
8Arrays and Pointers
- Closely related in C (not so in other language)
- Pointer is more efficient to use (array has catch
up with new compilers) - Insight into C
- Critical in mastering C
9Arrays and Pointers
a
int a int b4 int p int q p b0 p
5 p p 10 p b3 q p -1 q 3 p
- 3 if (p lt q) printf(d, p)
int a int b4 int p int q p b0 p
5 p p 10 p b3 q p -1 q 3 p
- 3 if (p lt q) printf(d, p)
5
10
b 5
b
(b1) 5
b b 3
3
q b-1
b -3
(bltq)
b
b)
10How do these pointers work?
11Array and Pointer (III)
- int a10 0,1,0,1,0,1,0,1
- int p
- int sum
- for (p a0 p lt a9 p)
- sum p
Equivalent
for (p a p lt a 9 p) sum p
12Array and Pointer (IV)
- Declaration int a10 is not equal to int a
- if p a can we use p2 to point to the third
element in array a?
13Multidimensional Array and Pointers (I)
A00
A01
A02
A03
- Pointers can point to multidimensional arrays too
- Row major
- E.g. char A33
A10
A11
A12
A13
A20
A21
A22
A23
A00 A01 A02 A03
A10 A11 A12 A13
A20 A21 A22 A23
14Multidimensional Array and Pointers (II)
A00
A01
A02
A03
- char p
- p A00
- How do we get to A01?
- p 1
- How do we get to A10?
- p 3
- How do we get to
- A23
- p 7 or
- p A23
A10
A11
A12
A13
A20
A21
A22
A23
A00 A01 A02 A03
A10 A11 A12 A13
A20 A21 A22 A23
15Multidimensional Array and Pointers (III)
- int a1010 0,1,0,1,0,1,0,1
- int p
- for (row 0 row lt 10 row)
- for (column 0 column lt 10 column)
- arowcolumn 0
Equivalent
for (p a00 p lt a99 p) p
0
16Multidimensional Array and Pointers (IV)
- Remember if
- int a10
- Then automatically pointer a points to a0
- (a is equivalent to a0)
- What about
- int b1010
- Is there an automatic pointer b?
- Yes, but b b0, not b00
- b is of type (int ) !! Pointer of pointers
17Summary
- Use of Pointers.
- Arrays and Pointers
18Before you go
- Read Chapter 12.
- Exercise 12.1, 12.7
- Homework 4 due tomorrow night, and late
submission on Thursday night.