Monday, 2 May 2011

Arrays and Strings

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:

int listofnumbers[50];

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:-


thirdnumber=listofnumbers[2];
listofnumbers[5]=100;

Multi-dimensional arrays can be defined as follows:

int tableofnumbers[50][50];

for two dimensions.

For further dimensions simply add more [ ]:

int bigD[50][50][40][30]......[50];

Elements can be accessed in the following ways:

anumber=tableofnumbers[2][3];
tableofnumbers[25][16]=100;

Strings

In C Strings are defined as arrays of characters. For example, the following defines a string of 50 characters:


char name[50];

C has no string handling facilities built in and so the following are all illegal:

char firstname[50],lastname[50],fullname[100];

firstname= "Arnold"; /* Illegal */
lastname= "Schwarznegger"; /* Illegal */
fullname= "Mr"+firstname
+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:

printf(``%s'',name);

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[50]; and we store the ``DAVE'' in it its contents will look like:

Name |D|A|V|E|\0|.....| |
0...............49

No comments:

Post a Comment