Practical Programming
The C Language :
Arrays and Strings
David Bouchet
david.bouchet.epita@gmail.com
1
Arrays
● An array is a collection of values that have the
same type.
● The size of an array is fixed (it cannot be
changed).
● An array can be either one-dimensional or
multidimensional.
● The most commonly used arrays are one-
dimensional and two-dimensional.
● Values are selected by integer indexes.
● Indexes always start at 0.
2
Declaring Arrays
a[0] = 0
a[1] = 0
a[2] = 0
a[3] = 0
a[4] = 4196000
a[5] = 0
a[6] = 4195552
a[7] = 0
a[8] = -1184014480
a[9] = 32766
----------------
a[0] = 5
a[1] = 5
a[2] = 5
a[3] = 5
a[4] = 5
a[5] = 5
a[6] = 5
a[7] = 5
a[8] = 5
a[9] = 5 3
Declaring and Initializing Arrays
a[0] = 2.000000
a[1] = 3.500000
a[2] = 7.800000
a[3] = 9.900000
a[4] = 2.000000
----------------
b[0] = 2.000000
b[1] = 3.500000
b[2] = 7.800000
b[3] = 9.900000
b[4] = 0.000000
4
Out of Bound Access – Reading
out_of_bound.c
$ gcc -Wall -Wextra out_of_bound.c
$ ./a.out
a[100] = -692211237
$ ./a.out
a[100] = -2024418853
$ ./a.out
a[100] = 1341063643
No compilation errors!
No compilation warnings!
Undefined behavior! 5
Out of Bound Access – Writing
out_of_bound.c
$ gcc -Wall -Wextra out_of_bound.c
$ ./a.out
Segmentation fault (core dumped)
No compilation errors!
No compilation warnings!
Segmentation fault (access violation)!
The program crashes! 6
Manipulating Arrays – Example
Average = 11.25
Min = 2
7
Two-Dimensional Arrays
mat[0][0] = 0
mat[0][1] = 1
mat[1][0] = 2
mat[1][1] = 3
mat[2][0] = 4
mat[2][1] = 5
-------------
arr[0][0] = 0
arr[0][1] = 1
arr[1][0] = 2
arr[1][1] = 3
arr[2][0] = 4
arr[2][1] = 5
8
Strings of Characters
● A string is an array of characters.
● A string is always terminated by a null character
(the ASCII code 0).
● Characters are selected by integer indexes.
● Indexes always start at 0.
9
Declaring Strings
s1 = Hello!
s2 = Hello!
s3 = Hello!
s4 = 3210
s5 = 3210
s1,
s1 s2 and s3 are identical.
s4 and s5 are identical.
Do not confuse ‘0’ (ASCII code: 48) and
0 (the null character ; ASCII Code: 0).
See also: table of escape sequences. 10
Manipulating Strings – Example
l1 = 5
l2 = 6
l3 = 3
buffer = Hello
buffer = World!
buffer = Bye
11
Command-Line Arguments
$ gcc -Wall -Wextra args.c
$ ./a.out
Number of arguments ......... 1
argv[0] (program name) ...... "./a.out"
$ ./a.out a bc "d e" " fg " h
Number of arguments ......... 6
argv[0] (program name) ...... "./a.out"
argv[1] ..................... "a"
args.c argv[2] ..................... "bc"
argv[3] ..................... "d e"
argv[4] ..................... " fg "
argv[5] ..................... "h"
12