86 Intermediate C Programming
The string in arr3 is “2nd st”. The character ’M’ is an array element but it is not part
of the string. Similarly, for arr4, the string is “C P @-”. The trailing characters ’1’ and ’8’
are elements of the array but they are not part of the string. We do not need to put any
number between [ and ] because gcc calculates the size for each array.
What is the difference between single quotation marks and double quotation marks?
Single quotations enclose a single letter, such as ’M’ and ’@’, and represent a character type.
Double quotations enclose a string and the null terminator, ’0’, is automatically added to
the end of the string. Thus, the string stored in arr3 is “2nd st” (no ’0’) but it actually
contains the element ’0’. Note that “W” is different from ’W’. The former uses double quotes
and means a string, ending with a null terminator even though it is not shown. Hence, “W”
actually means two characters. In contrast, ’W’ is a character without a null terminator.
To explain this in another way, when storing a string of n characters, the array needs
space for n + 1 characters. The additional character is used to store the terminating ’0’.
For example, to store the string “Hello” (5 characters), we need to create an array of 6
elements:
char arr [6]; /* create an array with 6 ch a racters */1
arr [0] = ’H ’;2
arr [1] = ’e ’;3
arr [2] = ’l ’;4
arr [3] = ’l ’;5
arr [4] = ’o ’;6
arr [5] = ’0 ’; /* reme mb er to add ’0’ */7
Forgetting the null terminator ’0’ is a common mistake. The null terminator
is important because it indicates the end (and thus length) of the string. In the earlier
examples, arr3 and arr4 were two arrays; arr3 had 8 elements and arr4 had 10 elements.
However, if they are treated as strings, the length of each is only 6. The null terminator is
not counted at part of the length. C provides a function strlen for calculating the length
of strings. Before calling strlen, the program needs to include the file string.h because
strlen and many string-related functions are declared in string.h.
// strlen . c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
#in clude < string .h >4
int main ( i n t argc , char * * argv )5
{6
char str1 [] = { ’T ’,’h ’, ’i ’ ,’s ’,’ ’, ’n’ ,’v ’,’t ’ };7
char str2 [] = { ’T ’,’h ’, ’i ’ ,’s ’,’ ’, ’s’ ,’t ’,’r ’ , ’0 ’ };8
char str3 [] = { ’2 ’,’n ’, ’d ’ ,’ ’,’s ’, ’t’ ,’0 ’, ’M ’ };9
char str4 [] = { ’C ’,’ ’, ’P ’ ,’ ’,’@ ’, ’-’ ,’0 ’, ’1 ’ ,’8 ’, ’k ’ };10
char str5 [6];11
int len3 ;12
int len4 ;13
int len5 ;14
str5 [0] = ’H ’;15
str5 [1] = ’e ’;16
str5 [2] = ’l ’;17
str5 [3] = ’l ’;18
str5 [4] = ’o ’;19
str5 [5] = ’0 ’;20
len3 = strlen ( str3 );21