Title: Chap' 5 Pointers and Arrays
1Chap. 5 Pointers and Arrays
- 5.1 Pointers and Adresses
- 5.2 Pointers and Function Arguments
- 5.3 Pointers and Arrays
- 5.4 Address Arithmetic
- 5.5 Character Pointers and Functions
- 5.6 Pointer Arrays Pointers to Pointers
- 5.7 Multidimensional Arrays
- 5.8 Initialization of Pointer Arrays
- 5.9 Pointers vs Multi-dimensional Arrays
- 5.10 Command-line Argument
- 5.11 Pointers to Functions
- 5.12 Complicated Declarations
Session 7 - 4 May 2004
Session 9 - 18 May 2004
!!! 11 May 2004 Mid Term Test !!!
Imperative Programming, B. Hirsbrunner,
diuf.unifr.ch/pai/ip04
25.1 Pointers and Addresses
- Pointer
- A pointer is a variable that contains the
address of a variable - Address Operator
- x is the address of the variable x
- Indirection or Dereferencing Operator
- p access the object the pointer p points to
A first example main() int x 1 int
p p x printf(d, p)
3A Mystery Program
Reminder
include ltstdio.hgt main() int i 1 int
p int q p i q p
printf("\nmystery d p p p", p0,
p0, p1, p2) p 3 printf("
p\r\n", p)
4Output of the Mystery Program
i 1 p BFFFFB08 q bffffb0c p 1
i BFFFFB08 p bffffb0c q 1 q
BFFFFB08 q bffffb10 i
1 i 0xbffffb08 p 1
p 0xbffffb08 mystery 1 0xbffffb08
0xbffffb0c 0xbffffb10 0xbffffb14
Memory Diagram
Full Memory Diagram
Reminder int i1 int pi int qp
55.2 Pointers and Function Arguments
- C passes arguments to functions by value !
65.3 Pointers and Arrays
As p is a variable, pa or p are legalbut as
an array name is not a variable, expression like
ap or a are illegal !
Tricky p-a is legal, but not pa !
7Array as a Parameter of a Function
// return length of string s int strlen(char
s) int n for (n 0 s ! '\0'
s) n return n
- The following calls will work
strlen(a) // char a10
strlen(p) // char p
strlen("hello world") // string constant !!
8A Test Program
- include ltstdio.hgt
- / Return length of string s /
- int strlen(char s)
-
- int n
-
- for (n 0 s ! '\0' s)
- n
- return n
-
- main()
-
- char a "hello"
- char p a
-
- (1) printf("d\n", strlen(a))
- (2) printf("d\n", strlen(p))
Hint Draw the execution diagram for (1), (2) and
(3)