1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995, 1996 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>section
1.6: Arrays
</title>
10 <link href=
"sx4i.html" rev=precedes
>
11 <link href=
"sx4k.html" rel=precedes
>
12 <link href=
"sx4.html" rev=subdocument
>
15 <H2>section
1.6: Arrays
</H2>
18 <p>Note carefully that arrays in C are
0-based,
19 not
1-based as they are in some languages.
21 (As we'll see,
0-based arrays turn out to be more convenient
22 than
1-based arrays more of the time,
23 but they may take a bit of getting used to at first.)
25 ``as reflected in the
<TT>for
</TT> loops
26 that initialize and print the array,''
27 they're referring to the fact that the vast majority of
28 <TT>for
</TT> loops in C look like this:
29 <pre> for(i =
0; i
< 10; ++i)
30 </pre>and count from
0 to
9.
32 <pre> for(i =
1; i
<=
10; ++i)
33 </pre>would count from
1 to
10, but loops like this are comparatively
35 (In fact, whenever you see either ``
<TT>=
1</TT>''
36 or ``
<TT><=
</TT>'' in a
<TT>for
</TT> loop,
37 it's an indication that something unusual is going on
38 which you'll want to be aware of,
39 and it may even be a bug.)
41 </p><p>They've started going a little fast here,
42 so read up if they're losing you.
43 What's this magic expression
<TT>c-'
0'
</TT>
44 that they're using as an array subscript?
45 Remember, as we saw first on page
19,
46 that characters in C are represented by small integers
47 corresponding to their values in the machine's character set.
48 In ASCII, which most machines use,
49 <TT>'A'
</TT> is character code
65,
50 <TT>'
0'
</TT> (zero) is code
48,
51 <TT>'
9'
</TT> is code
57,
52 and all the other characters have their own values which I won't
54 If we've just read the character
<TT>'
9'
</TT> from the file,
55 it has value
57, so
<TT>c-'
0'
</TT> is
57 -
48 which is
9,
56 and we'll increment cell number
9 in the array,
59 even if we're not using a machine which uses ASCII,
60 by subtracting
<TT>'
0'
</TT>,
61 we'll always subtract whatever the right value is to map the
62 characters from
<TT>'
0'
</TT> to
<TT>'
9'
</TT> down to the array cell
68 <a href=
"sx4i.html" rev=precedes
>prev
</a>
69 <a href=
"sx4k.html" rel=precedes
>next
</a>
70 <a href=
"sx4.html" rev=subdocument
>up
</a>
71 <a href=
"top.html">top
</a>
74 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
75 //
<a href=
"copyright.html">Copyright
</a> 1995,
1996
76 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>