'\0'
).
Suppose we have a character array called buf with 10 characters.
If buf
holds the string "Hello" as in the declaration:
char buf[10] = "Hello" ;
buf
as in this figure.
A few things should be noted about such strings:
![]() | The characters following the null byte are garbage; don't count
on them to have any specific value.
![]() Every array for holding a string must be at least one byte bigger
than the number of characters for the string it's to hold.
| |
Now let's put all this together and write a couple of routines to manipulate strings. First to find the length of a string we just need to count how many characters there are up to (but not including) the null byte.
int strlen( char *p ) { int len = 0 ; while( *p != '\0' ) { ++len ; ++p ; } return( len ) ; }
for
loop:
int strlen( char *p ) { int len ; for( len = 0; *p != '\0'; ++len, ++p ) ; return( len ) ; }
for
statement.
This indicates that there is no loop body for this loop.
This type of concise programming can be very simple for an experienced
programmer, but often causes confusion for beginners.
As a result there is some debate over which of these two forms would
be preferred stylistically.
As one last exercise and example, consider a function to make a fresh copy of a string:
char *fresh_copy( char *s ) { char *new, *p, *q ; new = (char *)malloc( strlen( s ) + 1 ) ; for( p = s, q = new; ( *q = *p ) != '\0'; ++p, ++q ) ; return( new ) ; }
Studying string operations is important in order to understand how they work, but because they are so common, many of the ones you'd want are already written for you. The UNIX man page string contains a complete list of the standard ones. Type the command
man stringat the UNIX prompt to see this description. (Warning: Much of the information in this man page is rather technical and will require some careful study. However, once the details are decoded, using the routines is fairly straightforward.)