Fundamentals of Programming
session 25
Array of pointers
Array of pointers
int *a[10];
char *s[20];
Array of pointers
arrayofpointers0.c
Array of pointers
arrayofpointers1.c
Array of pointers
arrayofpointers1.c
seasons[3]
seasons[2]
seasons[1]
seasons[0] 'S' 'p' 'r' 'i' 'n' 'g' 0
'S' 'p' 'r' 'i' 'n' 'g' 0 'F' 'a' 'l' 'l' 0
'S' 'p' 'r' 'i' 'n' 'g' 0
Array of pointers
arrayofpointers2.c
seasons[3]
seasons[2]
seasons[1]
seasons[0] 'S' 'p' 'r' 'i' 'n' 'g' 0
'S' 'p' 'r' 'i' 'n' 'g' 0 'F' 'a' 'l' 'l' 0
'S' 'p' 'r' 'i' 'n' 'g' 0
Array of pointers
arrayofpointers3.c
Array of pointers
arrayofpointers3.c
Referencing pointers of arrays
seasons[1][3] = ?
seasons[3]
seasons[2]
seasons[1]
seasons[0] 'S' 'p' 'r' 'i' 'n' 'g' 0
'S' 'p' 'r' 'i' 'n' 'g' 0 'F' 'a' 'l' 'l' 0
'S' 'p' 'r' 'i' 'n' 'g' 0
Referencing pointers of arrays
seasons[1][3]
= (seasons[1]) [3]
seasons[3]
seasons[2]
seasons[1]
seasons[0] 'S' 'p' 'r' 'i' 'n' 'g' 0
'S' 'p' 'r' 'i' 'n' 'g' 0 'F' 'a' 'l' 'l' 0
'S' 'p' 'r' 'i' 'n' 'g' 0
Referencing pointers of arrays
seasons[1][3]
= (seasons[1]) [3] = 'i'
seasons[3]
seasons[2]
seasons[1]
seasons[0] 'S' 'p' 'r' 'i' 'n' 'g' 0
'S' 'p' 'r' 'i' 'n' 'g' 0 'F' 'a' 'l' 'l' 0
'S' 'p' 'r' 'i' 'n' 'g' 0
Array of pointers
arrayofpointers4.c
Array of pointers
arrayofpointers4.c
Array of pointers vs. 2D arrays
3 2 1 0 Memory
13 12 11 10
23 22 21 20
3 2 1 0
13 12 11 10
23 22 21 20 a[2]
a[1]
a[0]
Array of pointers vs. 2D arrays
3 2 1 0 Memory
13 12 11 10
23 22 21 20
3 2 1 0
13 12 11 10
23 22 21 20 a[2]
a[1]
a[0]
● Advantages of array of pointers
○ Rows of different length (more flexibility, saving memory)
Array of pointers vs. 2D arrays
names[3]
names[2]
names[1]
names[0] 'A' 'k' 'b' 'a' 'r' 'i' 0
'A' 'l' 'a' 'v' 'o' 0 'N' 'a' 'r' 'i' 0
'B' 'i' 'a' 'k' 'i' 'A' 's' 'l' 'e' 'T' 'e' 'h' 'r' 'a 'n' 'i' 0
● Advantages of array of pointers
○ Rows of different length (more flexibility, saving memory)
Array of pointers vs. 2D arrays
Array of pointers vs. 2D arrays
3 2 1 0 Memory
13 12 11 10
23 22 21 20
3 2 1 0
13 12 11 10
22 21 20 14 a[2]
a[1]
a[0]
● Advantages of array of pointers
○ Rows of different length (more flexibility, saving memory)
○ Swapping two rows efficiently
Array of pointers vs. 2D arrays
names[3]
names[2]
names[1]
names[0] 'A' 'k' 'b' 'a' 'r' 'i' 0
'A' 'l' 'a' 'v' 'o' 0 'N' 'a' 'r' 'i' 0
'B' 'i' 'a' 'k' 'i' 'A' 's' 'l' 'e' 'T' 'e' 'h' 'r' 'a 'n' 'i' 0
● Advantages of 2D arrays
○ Efficiency (in accessing elements)