Previous: 11 String Processing
Up: 11 String Processing
Next: 11.2 Library String Functions
Previous Page: 11 String Processing
Next Page: 11.2 Library String Functions
Because a string is such a common data structure in programs, it may be convenient to define it as its own data type. We can then define functions to perform operations on operands of the defined data type; effectively treating the defined type as a new data type (an abstract data type). As we have seen previously, a string is implemented as an array of characters, and an array is implemented as a contiguous collection of cells and a pointer pointing to the beginning of the block. The name of the array is associated with this pointer cell, rather than with the data cells themselves. When we pass an array to a function, we pass this pointer to the array. So when we are processing strings, passing them to functions, returning them as values, we are handling pointer values. Therefore, we can define a data type, STRING, as a pointer to a character as follows:
typedef char * STRING;
We can then define string variables in terms of the data type, STRING:
STRING s, t;
The variables, s and t, are character pointers. We can access the characters in the string by dereferencing the pointer or using array type indexing. But remember, declaring a pointer type only allocates space for the pointer; it does not allocate cells for an array; it does not initialize the pointer. We cannot use a STRING variable to store a string of characters, but merely to point to a pre-allocated string. We must always declare a character array to store a string of characters, and can then initialize a STRING variable to point to this array. STRING does not serve to allocate memory for a string. As such, the concept of abstract data type is not totally satisfied by the above type definition; however, with the above caveat, we can otherwise treat it as such.
We illustrate the use of the STRING type by writing a rogram to read and print a string as shown in Figure 11.1. Note, in main(), a character array, s, is declared. The name of the array, s, is an (initialized) character pointer - the same as our type, STRING, and may therefore be passed to the function our_strprint() which expects a STRING argument. Notice, we have placed the typedef for STRING in a header file, strtype.h since it will be useful for other programs we will write.