next up previous
Next: November 29 Up: November 27 Previous: November 27


C strings

I present this material out-of-sequence since we needed some of the earlier topics in order to make assignments do-able. However, a few comments on how to treat strings in C is needed.

When you're finished, you should be able to say what the following code does, and why:

char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);} 
Can you do something similar without the magic number 34?

C doesn't truly have strings, it has arrays of char terminated by the special zero character '\0'. Once you've left the scope where an array of char was declared, C can't distinguish between char s[5] and char *s.

Here are a few C string functions you should become familiar with (see K.N. King for details). You need stdio.h' for the first two, and string.h for the others.

printf
You've already used this. The first argument is a (possibly) formatted string. The remaining arguments are addresses of objects, that are inserted into the formatted string wherever a conversion specifier (%-something) is found.
scanf
Use this to read space-delimited strings from standard in. It will read to the next whitespace or the string delimited '\0', so be sure you have enough room to hold expected input:
#include <stdio.h>

int main()
{
    char s1[80+1], *s2;
    scanf("%80s", s1); /* okay */
    scanf("%80s", s2); /* not okay */
    printf("Strings %s, %s\n", s1, s2);
    return 0;
}
strlen(char *s)
This returns the number of characters before the first occurrence of '\0' at address s.

strcpy(char *s1, const char *s2)
Copy characters from s2 to s1. It copies up to the first '\0' in s2, and has no way of checking whether there is enough room in s1 to accommodate these. User beware. Behaviour is undefined if s1 and s2 overlap.

strcmp(char *s1, char *s2)
The comparison s1 == s2 doesn't work (you're comparing pointers). What you really want to know is whether the characters preceding the first '\0' in s1 are the same as the corresponding characters in s2. This function tells you more: is s1 greater than (positive value returned), equal to (0 returned), or less than (negative value returned) s2 in alphabetical order.


next up previous
Next: November 29 Up: November 27 Previous: November 27
Danny Heap 2002-12-16