Monday, January 26, 2009

Character Arrays; Strings in C Language

Text is usually kept as an array of characters, as we did with line[ ] in the example above. By convention in C, the last character in a character array should be a `\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\0' to detect the end of a character array when printing it out with a `%s'.
We can copy a character array s into another t like this:
i = 0;
while( (t[i]=s[i]) != '\0' )
i++;
Most of the time we have to put in our own `\0' at the end of a string; if we want to print the line with printf, it's necessary. This code prints the character count before the line:
main( ) {
int n;
char line[100];
n = 0;
while( (line[n++]=getchar( )) != '\n' );
line[n] = '\0';
printf("%d:\t%s", n, line);
}
Here we increment n in the subscript itself, but only after the previous value has been used. The character is read, placed in line[n], and only then n is incremented.
There is one place and one place only where C puts in the `\0' at the end of a character array for you, and that is in the construction
"stuff between double quotes"
The compiler puts a `\0' at the end automatically. Text enclosed in double quotes is called a string; its properties are precisely those of an (initialized) array of characters.

No comments:

Post a Comment