What is a String?
One extremely useful application of pointers is their use with strings. A string is simply a list of characters; in fact, in C, you can represent a string as a character array. But a string can also be thought of a pointer to characters. Indeed, the standard declaration of a string variable is
char *
. You've already seen string literals: anything inside double quotes. But now you can use string variables as well.When you think of a string as a character array, there is one pitfall to watch out for. All strings in C must be terminated by the null character (
'\0'
, or ASCII code 0). Thus, any string you put into an array is going to be one element longer than you'd expect. Also, remember that spaces and newlines are characters just like anything else, and so also count!
The String Library
The library
string.h
defines several useful functions for dealing with string data. I will present some of the more useful of these functions here.
int strlen(char *str)
strlen
takes a string as its argument and returns the number of characters in the string, not including the terminating null character.
int strcmp(char *str1, char *str2)
This function compares the characters in two strings based on their numeric ASCII values. If the first string is determined to come "before" the second as according to this code, the function returns a negative number. If the opposite is true, it returns a positive number. If the two strings are equal, it returns zero. The function
strncmp(char *str1, char *str2, int n)
is similar, except that it compares at mostn
characters in the strings.
char *strcpy(char dest[], char *src)
This function copies the string
src
into the destination bufferdest
. It also writes the null character at the end of the buffer for you. The return value is the address of the buffer. As withstrcmp()
, there is a correspondingstrncpy()
function that works the same way.
char *strcat(char dest[], char *src)
This function copies the characters from
src
onto the end ofdest
. You can also use thestrncat()
function, which works the same as the functions above.
Back to Memory and Pointers | On to More About I/O | |
Back to the Outline |