Strings 95
The output of the program is:
argv[1] = This is his history book., strlen = 25
argv[2] = is, strlen = 2
is is his history book.
is his history book.
is history book.
istory book.
argv[2] occurs 4 times in argv[1].
Earlier we noted that spaces separate the command line arguments. If we enclose a
sentence in double quotation marks, the whole sentence is treated as a single argument,
as shown in this example. Lines 21 prints argv[1] and it is the whole sentence. Without
the quotation marks, “This” is argv[1] and “is” becomes argv[2], etc. We must use two
quotation marks; otherwise, the Terminal says:
Unmatched "
Below is the call stack for this example. It has been formatted to fit onto one page.
We have skipped the column for the frame because only one function is displayed. Line 25
assigns the value of argv[1] to ptr. This value is the address of argv[1][0], namely 116.
Symbol Address Value
argv[1][6] 122 s
argv[1][5] 121 i
argv[1][4] 120
argv[1][3] 119 s
argv[1][2] 118 i
argv[1][1] 117 h
argv[1][0] 116 T
argv[0][10] 115 ’0’
argv[0][9] 114 r
argv[0][8] 113 t
argv[0][7] 112 s
argv[0][6] 111 t
argv[0][5] 110 n
argv[0][4] 109 u
argv[0][3] 108 o
argv[0][2] 107 c
argv[0][1] 106 /
argv[0][0] 105 .
argv[2] 104 142
argv[1] 103 116
argv[0] 102 105
argv 101 102
argc 100 3
Symbol Address Value
count 146 0
ptr 145 116
argv[2][2] 144 ’0’
argv[2][1] 143 s
argv[2][0] 142 i
argv[1][25] 141 ’0’
argv[1][24] 140 .
argv[1][23] 139 k
argv[1][22] 138 o
argv[1][21] 137 o
argv[1][20] 136 b
argv[1][19] 135
argv[1][18] 134 y
argv[1][17] 133 r
argv[1][16] 132 o
argv[1][15] 131 t
argv[1][14] 130 s
argv[1][13] 129 i
argv[1][12] 128 h
argv[1][11] 127
argv[1][10] 126 s
argv[1][9] 125 i
argv[1][8] 124 h
argv[1][7] 123
Line 28 finds “is” in “This is his history book.” The first occurrence of “is” is at address
118. This line changes ptr’s value to 118. Since it is not NULL, counter increments. Line
31 prints the string starting at the address where “is” is found. Recall that strings are
terminated by a null byte, and thus the entire string is printed starting from address 118.
Line 33 increments ptr to 119. This allows us to continue to search for “is” in the rest of