Next: Passing arrays as Up: Arrays and Pointers Previous: Arrays and pointers

Character strings

This is an important common use of arrays. C has no separate type for strings, but uses an array of characters. As the length of a string cannot be pre-known, we need to find some way of marking where the array ends. C uses the NULL character (the all-zero bit pattern) for this.

A string is thus a null-terminated array of characters.

Example

When we use a string constant, such as "Answer is" inside a printf, the system creates 10 consecutive bytes, one for each of the nine characters and the tenth to hold a null. In effect we have an array for which:

  char a[10];
  a[0]= 'A';
  a[1]= 'n';
  a[2]= 's';
   ...
  a[8]= 's';
  a[9]= '\0';   /* NULL */

and of course you can explicitly create strings within arrays exactly as above. However, it is important to note that C does not support string assignment, so you cannot write

   a= "Answer is";

and get the expected result. In keeping with the overall C approach, these kinds of operations are supported in an associated library. You will need:

#include <strings.h>

to obtain the relevant library procedures. Try man 3 string for full details.



Next: Passing arrays as Up: Arrays and Pointers Previous: Arrays and pointers


maspjw@
Tue Sep 27 15:29:34 BST 1994