Topic : An introduction to C
Author : Tom Torfs
Page : << Previous 10  Next >>
Go to page :


= %lu\n",(unsigned long)strlen(s));

   strcat(s, " program");
   printf("s now = %s\n", s);
   printf("strlen(s) = %lu\n",(unsigned long)strlen(s));

   return 0;
}


The output of this program is:

s = strings
s[3] = i
s[7] = 0
strlen(s) = 7
s now = strings program
strlen(s) = 15

10.2. Arrays and strings
Because we are going to use string handling functions in this program, a new header file is included:

#include <string.h>

This header file declares several useful functions for dealing with strings, such as strcpy(), strlen() and strcat() which we use in this program (see below).
As usual, at the beginning of main() we find a variable definition:

   char s[20];

The new thing here is the [20]. This is a definition of an array. An array is simply a contiguous series of variables of the same type. In this case we define s to be an array of 20 chars. The number inside the brackets [ ] must be a constant. [*]
[*] Variable length arrays are proposed for the new C standard
Multi-dimensional arrays (e.g. one that has rows and columns) can be defined as, for example, int multiarray[100][50]; etc.
You can have arrays of any type of variable. However arrays of char are often used for a special purpose: strings. A string is basically just text. Some languages have direct support for a 'string' type, but C doesn't. A string is an array of char with a special feature: the end of the string is marked by a char with value 0. That means we need to allocate one additional byte to store this 0 terminator. The consequence for our example is that s is able to hold a string of at most 19 characters long, followed by the 0 terminator byte.

   strcpy(s, "strings");

The string s we've defined above doesn't contain any useful contents yet. As we've seen before (see 2. Hello World!) a string literal between double quotes (") can be used as contents for the string. You might be tempted to do something like this:

   s = "strings";          /* wrong! */

However, this doesn't work. C doesn't support assigning arrays (including strings) in this way. You must actually copy all the characters in the string literal into the string you wish to initialize. Fortunately there is a standard function to this: strcpy(), declared in string.h.
To copy string1 to string2 you would write:

   strcpy(string2, string1);    /* notice the order of the parameters! */

When you fill in the string variable (array of char) s for string2 and the string literal "strings" for string1 (not vice versa, as we've seen before you can't write to string literals, see 2. Hello World!), we have the code from our program.

   printf("s = %s\n", s);
   printf("s[3] = %c\n", s[3]);
   printf("s[7] = %d\n", s[7]);


The first line prints out the entire text contained in string variable s, by using printf() format specifier %s.
The second line prints out the character (element) with index 3 in the array. Such an element is written as arrayname[indexnumber]. You have to be careful with the index numbers, though: in C all counting starts from 0. So the 1st element really is element number 0, the 2nd element is element number 1, etc. This also means that s[20] would be the 21st element of our array, and since the array is only 20 elements long, this value is out of range and therefore not valid!
In our case the string variable contains the text "strings" followed by the 0 byte. Since s[3] is the 4th element of the array, thus the 4th character of the string, an 'i' is printed (the %c printf() format specifier is used to print a character).
The third line prints s[7], which is the 8th character of the string. Since the text is only 7 characters long, the 8th character is our 0 terminator byte. That's why it's printed using %d (integer value) instead of %c (the 0 terminator usually doesn't have a character representation).

   printf("strlen(s) = %lu\n",(unsigned long)strlen(s));

The strlen() function returns the length of a string (the number of characters it contains, the terminating 0 not included). It returns a size_t, which is some unsigned integer type capable of holding the size of an object.
Since there is no special printf() format specifier for size_t we typecast it to an unsigned long (see 4.2. Operators and typecasts) and use the %lu format specifier.

   strcat(s, " program");

The strcat() function is used to append text to an already existing string variable. To append string1 to string2 you would write:

   strcat(string2, string1);   /* notice order of parameters */

You must make sure the string (character array) is large enough to hold all characters + the 0 terminator byte after the append!
In our case we add the string literal " program" to our already existing string "strings". The resulting string will be 7 + 8 = 15 characters long, plus the 0 terminator this requires 16 elements. Since our array is 20 elements long, there is no problem.

   printf("s now = %s\n", s);
   printf("strlen(s) = %lu\n",(unsigned long)strlen(s));


Finally the new text contained in s is printed. This will of course be "strings program". The new string length is also printed. This will of course be larger than the previous value.10.3. The pointers program

/* prog10-2.c: pointers */

#include <stdio.h>

int main(void)
{
   int a[] = {1,2,3,5,7,11,13,17,19};
   int *p;

   printf("a[4] = %d\n", a[4]);

   printf("the address of the array = %p\n", (void *)a);
   printf("the address of element nr. 0 of the array = %p\n", (void *)&a[0]);
   printf("the address of element nr. 4 of the array = %p\n", (void *)&a[4]);

   p = a;

   printf("the value of the pointer = %p\n", (void *)p);
   printf("the value the pointer points at = %d\n", *p);

   p += 4;

   printf("the value of the pointer now = %p\n", (void *)p);
   printf("the value the pointer now points at = %d\n", *p);

   return 0;
}


The output of this program may be something like the following: (the address values and even their notations will most likely be entirely different on your system)

a[4] = 7
the address of the array = 00030760
the address of element nr. 0 of the array = 00030760
the address of element nr. 4 of the array = 00030770
the value of the pointer = 00030760
the value the pointer points at = 1
the value of the pointer now = 00030770
the value the pointer now points at = 7

10.4. Addresses and pointers
OK, now we're going to discuss the often feared pointers. Don't worry if the above program seems terribly difficult to you - your first encounter with pointers may be a bit confusing, but it shouldn't be that difficult to understand the concept and how to use them.
What's a pointer ? Well, every variable has to be stored somewhere in your computer's memory. The place where they are stored is called the address of the variable. Such an address is some sort of position value (its exact representation depends on your system, and shouldn't really matter).
Such an address value can of course be stored in another variable (which has its own, different, address). That's called a pointer. A pointer contains the position in memory (address) of another variable, so in effect 'points' to this variable. Now let's analyze the program line by line and explain things on the way:

   int a[] = {1,2,3,5,7,11,13,17,19};

This is a definition of an array (see previous section). However, it's different from the one we used in our strings example in 3 ways:
1) it is not an array of char, but an array of int
2) the array is initialized with values; the initialization is similar to that of a struct variable (see 6.1. The cars program). We have several values (one for every element of the array), separated by a comma and surrounded by braces { }.
3) there is no number inside the brackets [ ]; this means we let the compiler count the number of elements we initialize and allocate just enough memory to be able to store all these elements (in our case the compiler will count 9 initialized elements, and will allocate a 9 elements long array).

   int *p;

Another variable definition: the * indicates "is a pointer to". So we've defined p as a pointer to int, which means that p can hold the address value of an int variable. [*]
[*] If you need a generic pointer, not to any specific type of variable, you should use a pointer to void (void *). However, you can't do the sort of calculations with these sort of pointers that we're doing in this program.

   printf("a[4] = %d\n", a[4]);

This prints the

Page : << Previous 10  Next >>