Title: C Program Design C Pointers
1C Program DesignC Pointers
2Content
- Introduction
- Point Operators
- Calling Functions by References
- Pointer Expressions and Pointer Arithmetic
- Pointers and Arrays
- Using the const Qualifier with Pointers
- Arrays of Pointers
- Pointers to Functions
3C Program DesignC Pointers
4What is Pointer?
5CPU and Memory
6Memory Space
- Program and data are stored in some places of
memory. - Addresses (Pointers) are used to identify where
the program or data are stored. - CPU accesses a piece of memory data by emitting
its address on address bus.
address
7C Pointers
- Powerful, but difficult to master
- Simulate call-by-reference
- C only has call-by-value
-
- Close relationship with arrays and strings
- important for handling arrays and strings
8C Program DesignC Pointers
- Pointer Variable Definitions
- and Initialization
9Pointer Variables
Variable is a piece of memory containing a value
of a specific type (direct reference).
- Pointer variables contain memory addresses as
their values - Indirect reference ?
- Typed pointers point to the address of a variable
of a specific type - Non-typed pointers are simply addresses, i.e.,
they can point to an addresses of any thing
10Pointer Definitions
datatype pointerName
Examples
int ptr1 int ptr2, ptr3 char ptr4 double
ptr5 void ptr6, ptr7
Typed pointers
Non-typed pointers
11Pointer Definitions
datatype pointerName
Dont write as int ptr2, ptr3
Examples
int ptr1 int ptr2, ptr3 char ptr4 double
ptr5 void ptr6, ptr7
Typed pointers
Non-typed pointers
12Pointer Initialization
Where these pointers point to?
int ptr1 int ptr2, ptr3 char ptr4 double
ptr5 void ptr6, ptr7
13Pointer Initialization
Before pointers are actually used, it is a good
habit to initialize them to NULL, meaning that
they are pointing to nothing.
define NULL 0 int ptr1NULL int ptr2NULL,
ptr3NULL char ptr4NULL double
ptr5NULL void ptr6NULL, ptr7NULL
14C Program DesignC Pointers
15Point Operators
- Reference operator ()
- Retrieve the address of a variable
- Dereference operator ()
- Retrieve the value pointed by a pointer (address)
- and are inverses
- They cancel each other out
16Reference Operator ()
Nickname address-of operator
- Returns address-of operand
int n5 double x3.14 . . . . . int
nPtr double xPtr nPtr n xPtr x
n
x
. . .
nPtr
xPtr
17??
include ltstdio.hgt int n5 double x3.14 int
nPtr double xPtr main() / nPtr gets
address of n / nPtr n / xPtr gets
address of n / xPtr x
printf("Address of n is p\n" "Address
of x is p\n", nPtr, xPtr)
00427600
00427608
00427600
00427608
18??
- ????????main?????,????,??????????
include ltstdio.hgt int n5 double x3.14 int
nPtr double xPtr main() / nPtr gets
address of n / nPtr n / xPtr gets
address of n / xPtr x
printf("Address of n is p\n" "Address
of x is p\n", nPtr, xPtr)
00427600
00427608
00427600
00427608
19Dereference Operator ()
Nickname value-point-by operator
- Returns value point by operand
00427600
nPtr ? xPtr ?
00427608
00427600
00427608
20Dereference Operator ()
Nickname value-point-by operator
- Returns value point by operand
include ltstdio.hgt int n5 double x3.14 int
nPtr double xPtr main() / nPtr gets
address of n / nPtr n / xPtr gets
address of n / xPtr x
printf("integer value in address p is d\n"
"double value in address p is lf\n",
nPtr, nPtr, xPtr, xPtr)
00427600
nPtr ? xPtr ?
00427608
00427600
00427608
21??
Showing that and are complements of each
other.
include ltstdio.hgt int main( void ) int
a / a is an integer / int aPtr
/ aPtr is a pointer to an integer / a
7 aPtr a / aPtr set to address of a
/ printf( "The address of a is p"
"\nThe value of aPtr is p", a, aPtr )
printf( "\n\nThe value of a is d"
"\nThe value of aPtr is d", a, aPtr )
printf( "\n\nShowing that and are complements
of " "each other\naPtr p"
"\naPtr p\n", aPtr, aPtr )
return 0 / indicates successful termination
/ / end main /
22??
Showing that and are complements of each
other.
include ltstdio.hgt int main( void ) int
a / a is an integer / int aPtr
/ aPtr is a pointer to an integer / a
7 aPtr a / aPtr set to address of a
/ printf( "The address of a is p"
"\nThe value of aPtr is p", a, aPtr )
printf( "\n\nThe value of a is d"
"\nThe value of aPtr is d", a, aPtr )
printf( "\n\nShowing that and are complements
of " "each other\naPtr p"
"\naPtr p\n", aPtr, aPtr )
return 0 / indicates successful termination
/ / end main /
23??
- What is the data type of aPtr?
- Modify the following program to also show the
address of aPtr.
include ltstdio.hgt int main( void ) int
a / a is an integer / int aPtr
/ aPtr is a pointer to an integer / a
7 aPtr a / aPtr set to address of a
/ printf( "The address of a is p"
"\nThe value of aPtr is p", a, aPtr )
printf( "\n\nThe value of a is d"
"\nThe value of aPtr is d", a, aPtr )
printf( "\n\nShowing that and are complements
of " "each other\naPtr p"
"\naPtr p\n", aPtr, aPtr )
return 0 / indicates successful termination
/ / end main /
24C Program DesignC Pointers
- Calling Functions by Reference
25C Simple Swap Program
include ltstdio.hgt main() int a 23, b
47 int t printf("Before. a d, b
d\n", a, b) t a a b b t
printf("After. a d, b d\n", a, b)
26C Simple Swap Program
include ltstdio.hgt main() int a 23, b
47 int t printf("Before. a d, b
d\n", a, b) t a a b b t
printf("After. a d, b d\n", a, b)
define a function to do swapping.
27C Simple Swap Program
include ltstdio.hgt main() int a 23, b
47 printf("Before. a d, b d\n", a,
b) swap(a, b)
printf("After. a d, b d\n", a, b)
Workable?
28C Simple Swap Program
include ltstdio.hgt main() int a 23, b
47 printf("Before. a d, b d\n", a,
b) swap(a, b)
printf("After. a d, b d\n", a, b)
Workable?
29Calling Function by Passing References
include ltstdio.hgt main() int a 23, b
47 printf("Before. a d, b d\n", a,
b) swap(a, b)
printf("After. a d, b d\n", a, b)
Workable?
30Calling Function by Passing References
include ltstdio.hgt main() int a 23, b
47 printf("Before. a d, b d\n", a,
b) swap(a, b)
printf("After. a d, b d\n", a, b)
Workable?
31Review Bubble Sort
void BubbleSort(int data, int n) int tmp,
i, j for(i0 iltn-1 i) for(j0
jltn-i-1 j) if(dataj gt
dataj1) tmp dataj
dataj dataj1
dataj1
tmp
32Bubble Sort
void swap(int a, int b) int t t
a a b b t
void BubbleSort(int data, int n) int i,
j for(i0 iltn-1 i) for(j0
jltn-i-1 j) if(dataj gt
dataj1) swap(dataj,
dataj1)
33Pointers vs. Arrays
void swap(int a, int b) int t t
a a b b t void BubbleSort(int
data, int n) int i, j for(i0
iltn-1 i) for(j0 jltn-i-1 j)
if(dataj gt dataj1)
swap(dataj, dataj1) main() int
vals5100, 30, 20, 75, 15
BubbleSort(vals, 5) / ......................
...... /
int
int
int
34Pointers vs. Arrays
void swap(int a, int b) int t t
a a b b t void BubbleSort(int
data, int n) int i, j for(i0
iltn-1 i) for(j0 jltn-i-1 j)
if(dataj gt dataj1)
swap(dataj, dataj1) main() int
vals5100, 30, 20, 75, 15
BubbleSort(vals, 5) / ......................
...... /
int
void BubbleSort(int data, int n)
int
35C Program DesignC Pointers
- Pointer Expressions and Pointer Arithmetic
36Pointer Arithmetic
- Increment/decrement pointer
- or -
- Add/substract an integer to a pointer
- or , - or -
- Pointers may be subtracted from each other
37Pointer Arithmetic
May be meaningless unless performed on an array.
- Increment/decrement pointer
- or -
- Add/substract an integer to a pointer
- or , - or -
- Pointers may be subtracted from each other
38Pointer Arithmetic
- Increment/decrement pointer ( or -)
- Add/substract an integer to a pointer ( or ,
- or -) - Pointers may be subtracted from each other
int data10 int i for(i0 ilt10 i)
datai i
0
1
2
3
4
5
6
int data10 int i, p for(i0, pdata ilt10
i) p i p
7
8
9
39Pointer Arithmetic
- Increment/decrement pointer ( or -)
- Add/substract an integer to a pointer ( or ,
- or -) - Pointers may be subtracted from each other
Which one is performance more effective?
int data10 int i for(i0 ilt10 i)
datai i
0
1
2
3
4
5
6
int data10 int i, p for(i0, pdata ilt10
i) p i p
7
8
9
40Pointer Arithmetic
- Increment/decrement pointer ( or -)
- Add/substract an integer to a pointer ( or ,
- or -) - Pointers may be subtracted from each other
int data10 int i, p for(i0, pdata ilt10
i) p i
0
1
2
3
4
5
6
int data10 int i, p for(i0, pdata ilt10
i) p i p
7
8
9
41Pointer Arithmetic
- Increment/decrement pointer ( or -)
- Add/substract an integer to a pointer ( or ,
- or -) - Pointers may be subtracted from each other
int data10 int i, p for(i0, pdata ilt10
i) p i
0
1
2
3
4
5
6
7
int data10 int i, p for(i0, pdata ilt10
p i)
8
9
42??Insert/Delete Data into/from Arrays
void insertAt(int array, int size, int at, int
val) void deleteAt(int array, int size, int
at)
insertAt(data, 10, 3, 5)
deleteAt(data, 10, 5)
43??Insert/Delete Data into/from Arrays
/ arrayOp.c / / insertAt insert an element
into an int array / void insertAt(int array,
int size, int at, int val) int p, q
p arrayat q arraysize-1
while(q gt p) q (q-1) q--
p val / deleteAt delete an
element from an int array / void deleteAt(int
array, int size, int at) int p, q
p arrayat q arraysize-1
while(p lt q) p (p1) p
44??Insert/Delete Data into/from Arrays
/ main.c / void insertAt(int array, int size,
int at, int val) void deleteAt(int array, int
size, int at) void listElements(int array, int
size) main() int data 0, 1, 2, 3, 4,
5, 6, 7, 8, 9 printf("Origin data\n")
listElements(data, 10) insertAt(data, 10,
3, 5) printf("After calling insertAt(data,
10, 3, 5)\n") listElements(data, 10)
deleteAt(data, 10, 5) printf("After calling
deleteAt(data, 10, 5)\n")
listElements(data, 10)
45??Pointer Arithmetic
include ltstdio.hgt main() int data0,
1, 2, 3, 4, 5, 6, 7, 8, 9 int p, q
printf("data0, 1, 2, 3, 4, 5, 6, 7, 8,
9\n\n") p q data printf("p q
data gt p q p\n", data) printf("q - p
d\n\n", q - p) p q 5
printf("p q 5 gt p p, q p\n", p, q)
printf("q - p d\n\n", q - p) p - 3
q-- printf("p - 3 q-- gt p p, q
p\n", p, q) printf("q - p d\n\n", q -
p)
46??Pointer Arithmetic
include ltstdio.hgt main() int data0,
1, 2, 3, 4, 5, 6, 7, 8, 9 int p, q
printf("data0, 1, 2, 3, 4, 5, 6, 7, 8,
9\n\n") p q data printf("p q
data gt p q p\n", data) printf("q - p
d\n\n", q - p) p q 5
printf("p q 5 gt p p, q p\n", p, q)
printf("q - p d\n\n", q - p) p - 3
q-- printf("p - 3 q-- gt p p, q
p\n", p, q) printf("q - p d\n\n", q -
p)
47Pointer Comparison
- lt, lt, , gt, gt
- Usually, they apply to pointers of arrays
element - p ? q is true iff p - q ? 0 is true, e.g.,
- p lt q is true iff p q lt 0 is true
- p gt q is true iff p q gt 0 is true
- NULL p ? Test the validity of p, e.g.,
- define NULL 0
- int p NULL
- / p may point to somewhere in the following /
- . . . . . . . . . . . . . . .
- if (NULLp) printf("p is an invalid pointer")
- else printf("d\n", p)
48Pointer Casting
- Pointers of the same type can be assigned to each
other - If not the same type, a cast operator must be
used - Example
main() int m5 int p, q char
r p m / ok / q p / ok /
r p / warning /
49Pointer Casting
- Pointers of the same type can be assigned to each
other - If not the same type, a cast operator must be
used - Example
main() int m5 int p, q char
r p m / ok / q p / ok /
r (char ) p / ok /
50??Pointer Casting
main() int m int p, q char
r m 0x1ff / 511 / printf("integer
m d\n\n", m) p m / ok / q p
/ ok / r (char ) p / ok /
printf("p, q, r all point to m\n")
printf("pp, qp, rp\n", p, q, r)
printf("pd, qd, rd\n\n", p, q, r)
r '\0' printf("After setting the 1st
byte of m zero, then\n") printf("pd,
qd, rd\n", p, q, r)
ff
?00
01
00
00
51??Pointer Casting
main() int m int p, q char
r m 0x1ff / 511 / printf("integer
m d\n\n", m) p m / ok / q p
/ ok / r (char ) p / ok /
printf("p, q, r all point to m\n")
printf("pp, qp, rp\n", p, q, r)
printf("pd, qd, rd\n\n", p, q, r)
r '\0' printf("After setting the 1st
byte of m zero, then\n") printf("pd,
qd, rd\n", p, q, r)
ff
?00
01
00
00
52Non-Typed Pointer ? void
- Generic pointer, represents any type
- No casting needed to convert a pointer to void
pointer - void pointers cannot be dereferenced, e.g.,
int m5, n char c'a', d void p p m /
ok / n p / invalid / p c / ok / d
p / invalid /
int m5, n char c'a', d void p p m /
ok / n (int ) p / ok / p c / ok
/ d (char ) p / ok /
53C Program DesignC Pointers
54Pointers vs. Arrays
- Arrays and pointers closely related
- Array name like a constant pointer
- Pointers can do array subscripting operations
55??Pointers vs. Arrays (I)
- Arrays and pointers closely related
- Array name like a constant pointer
- Pointers can do array subscripting operations
include ltstdio.hgt main() int data2,
-1, 60, 90, 35 int p, i p data /
or p data0 / printf("p
data0\n") for(i0 ilt5 i)
printf("datadd\tpdd\t\t(pd)d\n",
i, datai, i, pi, i, (pi))
p data0 ?
pointer-offset notation
56??Pointers vs. Arrays (II)
- Arrays and pointers closely related
- Array name like a constant pointer
- Pointers can do array subscripting operations
include ltstdio.hgt main() int data2,
-1, 60, 90, 35 int p, i p data /
or p data0 / printf("p
data0\n") for(i0 ilt5 i, p)
printf("datadd\tpp\tpd\n", i, datai,
p, p)
57??Pointers vs. Arrays (III)
- Arrays and pointers closely related
- Array name like a constant pointer
- Pointers can do array subscripting operations
include ltstdio.hgt main() int data2,
-1, 60, 90, 35 int p, i p data /
or p data0 / printf("p
data0\n") for(i0 ilt5 i)
printf("datadd\tpp\tpd\n", i,
datai, p, p)
58??Pointers vs. Arrays (IV)
- Arrays and pointers closely related
- Array name like a constant pointer
- Pointers can do array subscripting operations
include ltstdio.hgt main() int data2,
-1, 60, 90, 35 int p, i p data /
or p data0 / printf("p
data0\n") for(i0 ilt5 i, data,
p) printf("datad\tpd\n",data,
p)
59??String Copy (I)
include ltstdio.hgt void stringCopy(char dest,
const char source) main() char
string110 / create a string buffer
of size 10 / char string2"Hello" /
create a string using pointer notation /
char string310 / create a string
buffer of size 10 / char string4"Good
Bye" / create a string using array notation
/ stringCopy(string1, string2)
printf("string1s\n", string1)
stringCopy(string3, string4)
printf("string3s\n", string3) void
stringCopy(char dest, const char source)
while(source!'\0') dest source
dest source dest'\0'
60??String Copy (II)
include ltstdio.hgt void stringCopy(char dest,
const char source) main() char
string110 / create a string buffer
of size 10 / char string2"Hello" /
create a string using pointer notation /
char string310 / create a string
buffer of size 10 / char string4"Good
Bye" / create a string using array notation
/ stringCopy(string1, string2)
printf("string1s\n", string1)
stringCopy(string3, string4)
printf("string3s\n", string3) void
stringCopy(char dest, const char source)
while(source) dest source
dest'\0'
61??String Copy (III)
include ltstdio.hgt void stringCopy(char dest,
const char source) main() char
string110 / create a string buffer
of size 10 / char string2"Hello" /
create a string using pointer notation /
char string310 / create a string
buffer of size 10 / char string4"Good
Bye" / create a string using array notation
/ stringCopy(string1, string2)
printf("string1s\n", string1)
stringCopy(string3, string4)
printf("string3s\n", string3) void
stringCopy(char dest, const char source)
while(dest source)
strcpy
62??String Length
/ non-recursive version / int
stringLength(const char s) int len0
while(s) len return len /
recursive version / int recursiveStringLength(con
st char s) if(s'\0') return 0
return recursiveStringLength(s) 1
63??atoi(recurive version)
// RecursiveAtoi.c // recursive_atoi convert a
decimal string (str) // into an integer with
leading value (leading_val) int
recursive_atoi(const char str, int
leading_val) if(strstart '-')
return -recursive_atoi(str, val, start1)
else if(strstart '') return
recursive_atoi(str, val, start1) else
if(strstart'\0') return val
else return recursive_atoi(str, val 10
(strstart - '0'), start1) // atoi
convert a decimal string str into an integer //
assume str is error free int atoi(const char
str) return recursive_atoi(str, 0, 0)
leading_val125
64??atoi(recurive version)
// RecursiveAtoi.c // recursive_atoi convert a
decimal string (str) // into an integer with
leading value (leading_val) int
recursive_atoi(const char str, int
leading_val) if(strstart '-')
return -recursive_atoi(str, val, start1)
else if(strstart '') return
recursive_atoi(str, val, start1) else
if(strstart'\0') return val
else return recursive_atoi(str, val 10
(strstart - '0'), start1) // atoi
convert a decimal string str into an integer //
assume str is error free int atoi(const char
str) return recursive_atoi(str, 0)
'1'
'2'
'5'
'9'
'3'
'0'
'1'
'9'
'\0'
leading_val0
65??atoi(recurive version)
// RecursiveAtoi.c // recursive_atoi convert a
decimal string (str) // into an integer with
leading value (leading_val) int
recursive_atoi(const char str, int
leading_val) if(strstart '-')
return -recursive_atoi(str, val, start1)
else if(strstart '') return
recursive_atoi(str, val, start1) else
if(strstart'\0') return val
else return recursive_atoi(str, val 10
(strstart - '0'), start1) // atoi
convert a decimal string str into an integer //
assume str is error free int atoi(const char
str) return recursive_atoi(str, 0)
leading_val12593019
'1'
'2'
'5'
'9'
'3'
'0'
'1'
'9'
'\0'
? answer
66??atoi(recurive version)
// RecursiveAtoi.c // recursive_atoi convert a
decimal string (str) // into an integer with
leading value (leading_val) int
recursive_atoi(const char str, int
leading_val) if(strstart '-')
return -recursive_atoi(str, val, start1)
else if(strstart '') return
recursive_atoi(str, val, start1) if(str
'\0') return leading_val else
return recursive_atoi(str, leading_val 10
(str - '0')) // atoi convert a
decimal string str into an integer // assume str
is error free int atoi(const char str)
return recursive_atoi(str, 0)
67??atoi(recurive version)
// RecursiveAtoi.c // recursive_atoi convert a
decimal string (str) // into an integer with
leading value (leading_val) int
recursive_atoi(const char str, int
leading_val) if(str '-') return
-recursive_atoi(str, leading_val) else
if(str '') return recursive_atoi(st
r, leading_val) else if(str '\0')
return leading_val else return
recursive_atoi(str, leading_val 10 (str -
'0')) // atoi convert a decimal string
str into an integer // assume str is error
free int atoi(const char str) return
recursive_atoi(str, 0)
68??atoi(recurive version)
// main.c include ltstdio.hgt int atoi(const
char) main() char str20
printf("Enter a numeric string")
scanf("s", str) printf("The value you type
isd\n", atoi(str))
// RecursiveAtoi.c // recursive_atoi convert a
decimal string (str) // into an integer with
leading value (leading_val) int
recursive_atoi(const char str, int
leading_val) if(str '-') return
-recursive_atoi(str, leading_val) else
if(str '') return recursive_atoi(st
r, leading_val) else if(str '\0')
return leading_val else return
recursive_atoi(str, leading_val 10 (str -
'0')) // atoi convert a decimal string
str into an integer // assume str is error
free int atoi(const char str) return
recursive_atoi(str, 0)
69C Program DesignC Pointers
- Using the const Qualifier with Pointers
70const Qualifier
- const qualifier
- Variable cannot be changed
- Use const if function does not need to change a
variable - Attempting to change a const variable produces an
error - const pointers
- Point to a constant memory location
- Must be initialized when defined
- int const myPtr x
- Type int const ? constant pointer to an int
- const int const Ptr x
- const pointer to a const int
- x itself can be changed, but not Ptr
- const int myPtr x
- Modifiable pointer to a const int
71??
include ltstdio.hgt include ltctype.hgt void
convertToUppercase( char sPtr ) main()
char string "characters and 32.98"
printf( "The string before conversion is s",
string ) convertToUppercase( string )
printf( "\nThe string after conversion is s\n",
string ) / convert string to uppercase
letters / void convertToUppercase( char sPtr
) while (sPtr) if(islower(sPtr))
sPtr toupper( sPtr ) sPtr
Both sPtr and sPtr are modifiable
72??
include ltstdio.hgt include ltctype.hgt void
convertToUppercase( char sPtr ) main()
char string "characters and 32.98"
printf( "The string before conversion is s",
string ) convertToUppercase( string )
printf( "\nThe string after conversion is s\n",
string ) / convert string to uppercase
letters / void convertToUppercase( char sPtr
) while (sPtr) if(islower(sPtr))
sPtr toupper( sPtr ) sPtr
73??
include ltstdio.hgt include ltctype.hgt void
convertToUppercase( const char sPtr )
main() char string "characters and
32.98" printf( "The string before
conversion is s", string )
convertToUppercase( string ) printf( "\nThe
string after conversion is s\n", string )
/ convert string to uppercase letters
/ void convertToUppercase( const char sPtr )
while (sPtr) if(islower(sPtr))
sPtr toupper( sPtr ) sPtr
sPtr is modifiable, while sPtr is not
?
74??
include ltstdio.hgt include ltctype.hgt void
convertToUppercase(char const sPtr )
main() char string "characters and
32.98" printf( "The string before
conversion is s", string )
convertToUppercase( string ) printf( "\nThe
string after conversion is s\n", string )
/ convert string to uppercase letters
/ void convertToUppercase(char const sPtr )
while (sPtr) if(islower(sPtr))
sPtr toupper( sPtr ) sPtr
sPtr is modifiable, while sPtr is not
?
75??
include ltstdio.hgt include ltctype.hgt void
convertToUppercase(char const sPtr )
main() char string "characters and
32.98" printf( "The string before
conversion is s", string )
convertToUppercase( string ) printf( "\nThe
string after conversion is s\n", string )
/ convert string to uppercase letters
/ void convertToUppercase(char const sPtr )
while (sPtr) if(islower(sPtr))
sPtr toupper( sPtr ) sPtr
void convertToUppercase( char const sPtr )
int i0 while (sPtri)
if(islower(sPtr)) sPtri toupper( sPtri )
i
?
76??
include ltstdio.hgt include ltctype.hgt void
convertToUppercase(const char const sPtr )
main() char string "characters and
32.98" printf( "The string before
conversion is s", string )
convertToUppercase( string ) printf( "\nThe
string after conversion is s\n", string )
/ convert string to uppercase letters
/ void convertToUppercase(const char const
sPtr ) while (sPtr)
if(islower(sPtr)) sPtr toupper( sPtr )
sPtr
Boths sPtr and sPtr are not modifiable.
?
?
77C Program DesignC Pointers
78Arrays of Pointers
- Arrays can contain pointers
- For example an array of strings
- char suit 4
- "Hearts", "Diamonds", "Clubs", "Spades
-
- Strings are pointers to the first character
- char ? each element of suit is a pointer to a
char - The strings are not actually stored in the array
suit, only pointers to the strings are stored
79Arrays of Pointers
- Arrays can contain pointers
- For example an array of strings
- char suit 4
- "Hearts", "Diamonds", "Clubs", "Spades
-
- Strings are pointers to the first character
- char ? each element of suit is a pointer to a
char - The strings are not actually stored in the array
suit, only pointers to the strings are stored
80??
/ playcard.c / include ltstdio.hgt void
showCard(int card) static const char
suit4 "Hearts", "Diamonds",
"Clubs", "Spades static const char
face13 "Ace",
"Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"
printf("5s of -8s", facecard13,
suitcard/13) void shuffle(int deck)
int i, n, t for(i52 i gt 1 i--)
n rand() i t deckn
deckn decki-1 decki-1 t
81??
/ playcard.c / include ltstdio.hgt void
showCard(int card) static const char
suit4 "Hearts", "Diamonds",
"Clubs", "Spades static const char
face13 "Ace",
"Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"
printf("5s of -8s", facecard13,
suitcard/13) void shuffle(int deck)
int i, n, t for(i52 i gt 1 i--)
n rand() i t deckn
deckn decki-1 decki-1 t
include ltstdio.hgt include ltstdlib.hgt include
lttime.hgt void shuffle(int) void
showCard(int) int deck52 main() int
i srand( (unsigned)time( NULL ) )
for(i0 ilt52 i) deckii
shuffle(deck) for(i0 ilt52 i)
showCard(decki) printf("s", i 2 ?
"\n" "\t")
82??
/ playcard.c / include ltstdio.hgt void
showCard(int card) static const char
suit4 "Hearts", "Diamonds",
"Clubs", "Spades static const char
face13 "Ace",
"Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"
printf("5s of -8s", facecard13,
suitcard/13) void shuffle(int deck)
int i, n, t for(i52 i gt 1 i--)
n rand() i t deckn
deckn decki-1 decki-1 t
include ltstdio.hgt include ltstdlib.hgt include
lttime.hgt void shuffle(int) void
showCard(int) int deck52 main() int
i srand( (unsigned)time( NULL ) )
for(i0 ilt52 i) deckii
shuffle(deck) for(i0 ilt52 i)
showCard(decki) printf("s", i 2 ?
"\n" "\t")
83C Program DesignC Pointers
84Array Names and Function Names
Arrays name denotes the starting address of the
arrays data
data
int data10 int main() . . . . . int
fun() . . . . .
main
Functions name denotes the starting address of
the functions code
fun
85Array Names and Function Names
Arrays name denotes the starting address of the
arrays data
data
int data10 int main() . . . . . int
fun() . . . . .
main
Functions name denotes the starting address of
the functions code
fun
86Pointers to Functions
- Pointer to function
- A variable contains the address of function
- Similar to how array name is address of first
element - Function name is starting address of code that
defines function - Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
87??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void bubbleSort(int data, int n)
int tmp, i, j for(i0
iltn-1 i) for(j0 jltn-i-1 j)
if(dataj gt dataj1) tmp
dataj
dataj dataj1
dataj1 tmp
88??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void bubbleSort(int data, int n) int tmp,
i, j for(i0 iltn-1 i) for(j0
jltn-i-1 j) if(dataj gt
dataj1) tmp dataj
dataj dataj1
dataj1
tmp
Sort the array into ascendant order
How to make the order descendant?
89??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void bubbleSort(int data, int n) int tmp,
i, j for(i0 iltn-1 i) for(j0
jltn-i-1 j) if(dataj gt
dataj1) tmp dataj
dataj dataj1
dataj1
tmp
The resulting order depends on how compare is
coded.
Can compare be a parameter?
if( compare(dataj, dataj1) )
compare
90??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void bubbleSort(int data, int n) int tmp,
i, j for(i0 iltn-1 i) for(j0
jltn-i-1 j) if(dataj gt
dataj1) tmp dataj
dataj dataj1
dataj1
tmp
How?
What type is it?
compare is a function pointer, i,e., it
represents the starting address of a function
which has the following prototype int xxx(int,
int)
Can compare be a parameter?
if( compare(dataj, dataj1) )
compare
91??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
compare
void bubbleSort(int data, int n, int
(compare)(int, int)) int tmp, i, j
for(i0 iltn-1 i) for(j0 jltn-i-1
j) if(dataj gt dataj1)
tmp dataj
dataj dataj1
dataj1 tmp
compare is a function pointer, i,e., it
represents the starting address of a function
which has the following prototype int xxx(int,
int)
if( compare(dataj, dataj1) )
compare
92??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
Some syntax variations
compare
void bubbleSort(int data, int n, int
(compare)(int, int)) int tmp, i, j
for(i0 iltn-1 i) for(j0 jltn-i-1
j) if( (compare)(dataj,
dataj1) ) tmp dataj
dataj
dataj1
dataj1 tmp
compare is a function pointer, i,e., it
represents the starting address of a function
which has the following prototype int xxx(int,
int)
compare
The version in the textbook
93??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
Some syntax variations
compare
void bubbleSort(int data, int n, int
compare(int, int)) int tmp, i, j
for(i0 iltn-1 i) for(j0 jltn-i-1
j) if( compare(dataj, dataj1)
) tmp dataj
dataj dataj1
dataj1 tmp
NaĂŻve version
compare
94??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void bubbleSort(int data, int n, int
(compare)(int, int)) int tmp, i, j
for(i0 iltn-1 i) for(j0 jltn-i-1
j) if( (compare)(dataj,
dataj1) ) tmp dataj
dataj
dataj1
dataj1 tmp
include ltstdio.hgt int compare_ascending(int a,
int b) return a gt b int
compare_descending(int a, int b) return a lt
b void listElements(int vals, int size)
int i for(i0 iltsize i) printf("d ",
valsi) printf("\n")
95??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void bubbleSort(int data, int n, int
(compare)(int, int)) int tmp, i, j
for(i0 iltn-1 i) for(j0 jltn-i-1
j) if( (compare)(dataj,
dataj1) ) tmp dataj
dataj
dataj1
dataj1 tmp
include ltstdio.hgt void bubbleSort(int data,
int n, int (compare)(int, int)) int
compare_ascending(int a, int b) int
compare_descending(int a, int b) void
listElements(int vals, int size) main()
int data10, 90, 25, 64, 55, 102, 5, 70, 35,
12 printf("Before sorting\n")
listElements(data, sizeof(data)/sizeof(int))
BubbleSort(data, sizeof(data)/sizeof(int),
compare_ascending) printf("sort in ascending
order\n") listElements(data,
sizeof(data)/sizeof(int)) BubbleSort(data,
sizeof(data)/sizeof(int), compare_descending)
printf("sort in descending order\n")
listElements(data, sizeof(data)/sizeof(int))
include ltstdio.hgt int compare_ascending(int a,
int b) return a gt b int
compare_descending(int a, int b) return a lt
b void listElements(int vals, int size)
int i for(i0 iltsize i) printf("d ",
valsi) printf("\n")
compare_ascending
compare_descending
96??Bubble Sort
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void bubbleSort(int data, int n, int
(compare)(int, int)) int tmp, i, j
for(i0 iltn-1 i) for(j0 jltn-i-1
j) if( (compare)(dataj,
dataj1) ) tmp dataj
dataj
dataj1
dataj1 tmp
include ltstdio.hgt void bubbleSort(int data,
int n, int (compare)(int, int)) int
compare_ascending(int a, int b) int
compare_descending(int a, int b) void
listElements(int vals, int size) main()
int data10, 90, 25, 64, 55, 102, 5, 70, 35,
12 printf("Before sorting\n")
listElements(data, sizeof(data)/sizeof(int))
BubbleSort(data, sizeof(data)/sizeof(int),
compare_ascending) printf("sort in ascending
order\n") listElements(data,
sizeof(data)/sizeof(int)) BubbleSort(data,
sizeof(data)/sizeof(int), compare_descending)
printf("sort in descending order\n")
listElements(data, sizeof(data)/sizeof(int))
include ltstdio.hgt int compare_ascending(int a,
int b) return a gt b int
compare_descending(int a, int b) return a lt
b void listElements(int vals, int size)
int i for(i0 iltsize i) printf("d ",
valsi) printf("\n")
97??
- ??Sorting??????????????????,?????????????????,????
??,??????bubbleSort()??????
98??Say Tone
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
include ltstdio.hgt / shouting / void
say_loud(char a_message) printf("\"s!!!\"
you shout.\n", a_message) / whispering
/ void say_soft(char a_message)
printf("\"s\" you whisper.\n", a_message)
99??Say Tone
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
void say_loud(char a_message) void say_soft(char
a_message) / say function pointer / void
(say)(char a_message) NULL int
main(void) / shout / say say_loud
/ or say say_loud / say("WHAT") /
or (say)("WHAT") / / whisper / say
say_soft / or say say_soft /
say("I know a secret!") / or (say)("I know a
secret!") /
100??Array of Function Pointers
- Function pointers can be
- Passed to functions
- Assigned to other function pointers
- Stored in arrays
/ arith.c / int sum(int a, int b) return a
b int subtract(int a, int b) return a -
b int mul(int a, int b) return a
b int div(int a, int b) if(b) return a /
b else return 0
include ltstdio.hgt include "arith.h" int
(arith4)(int x, int y)sum, substract, mul,
div main() int val1, val2, op
printf("Enter two numbers ") scanf("d d",
val1, val2) printf("0 Add, 1 Subtract,
2 Multiply, 3 Divide\n") do
printf("Enter number of operation ")
scanf("d", op) while(oplt0 opgt3)
printf("d", (arithop)(val1, val2))
/ arith.h / int sum(int a, int b) int
subtract(int a, int b) int mul(int a, int
b) int div(int a, int b)