Arrays and Strings
In principle arrays in C are similar to those found in other languages. As we shall shortly see arrays are defined slightly differently and there are many subtle differences due the close link between array and pointers. We will look more closely at the link between pointer and arrays later in Chapter 9.
Single and Multi-dimensional Arrays
Let us first look at how we define arrays in C:
BEWARE: In C Array subscripts start at 0 and end one less than the array size. For example, in the above case valid subscripts range from 0 to 49. This is a BIG difference between C and other languages and does require a bit of practice to get in the right frame of mind.
Elements can be accessed in the following ways:-
Multi-dimensional arrays can be defined as follows:
for two dimensions.
For further dimensions simply add more [ ]:
Elements can be accessed in the following ways:
In C Strings are defined as arrays of characters. For example, the following defines a string of 50 characters:
C has no string handling facilities built in and so the following are all illegal:
firstname= "Arnold"; /* Illegal */
lastname= "Schwarznegger"; /* Illegal */
+lastname; /* Illegal */
However, there is a special library of string handling routines which we will come across later.
To print a string we use printf with a special %s control character:
NOTE: We just need to give the name of the string.
In order to allow variable length strings the $\backslash$0 character is used to indicate the end of a string.
So we if we have a string, char NAME; and we store the ``DAVE'' in it its contents will look like:
Name |D|A|V|E|\0|.....| |