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.
'\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; }
'\0'
at address s.
'\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.
'\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.