diff options
author | zlg <zlg@zlg.space> | 2013-08-29 06:29:09 -0500 |
---|---|---|
committer | zlg <zlg@zlg.space> | 2013-08-29 06:29:09 -0500 |
commit | 6484527cec80136b09288abb1583046f5b776411 (patch) | |
tree | c3a715b426801ec72a82a92abea7cd9687aa59d7 /ch5 | |
parent | Solve Exercise 5-2: getfloat() (diff) | |
download | knr-6484527cec80136b09288abb1583046f5b776411.tar.gz knr-6484527cec80136b09288abb1583046f5b776411.tar.bz2 knr-6484527cec80136b09288abb1583046f5b776411.tar.xz knr-6484527cec80136b09288abb1583046f5b776411.zip |
Solve Exercise 5-3: pointer-powered strcat()
Diffstat (limited to 'ch5')
-rw-r--r-- | ch5/5-03_strcatp.c | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/ch5/5-03_strcatp.c b/ch5/5-03_strcatp.c new file mode 100644 index 0000000..9bfc336 --- /dev/null +++ b/ch5/5-03_strcatp.c @@ -0,0 +1,42 @@ +#include <stdio.h> + +/* The C Programming Language, 2nd Edition + * + * Exercise 5-3: Write a pointer version of the function strcat that we showed + * in Chapter 2: strcat(s,t) copies the string t to the end of s. + * + * Answer: Pay careful attention to the passage before this exercise; there's + * a difference between a character array and a pointer to a string constant. + * The major difference is you can modify the contents of a character array. + * String constants, like other constants, can't be modified. This practically + * requires that the first argument to strcatp is a character array. + * + * When working with pointers, details seem to be of utmost importance. + * + * Thanks to Chris and dagle from Freenode's ##c for their input on + * improving the code. + */ + +#define ALLOC 80 + +void strcatp(char *s, char *t); + +int main(void) { + char foo[ALLOC] = "This is amazing!"; + char *bar = " Pointers for everyone!"; + strcatp(foo, bar); + printf("%s\n", foo); + return 0; +} + +/* strcat: copy t into s; s must be large enough */ +void strcatp(char *s, char *t) { + while (*s != '\0') { + s++; + } + /* Doing this without checking a buffer means it may screw up memory. + * It's the programmer's duty to ensure this doesn't happen, not the + * function's. + */ + while ((*s++ = *t++)); +} |