Created
April 12, 2011 01:42
-
-
Save penryu/914764 to your computer and use it in GitHub Desktop.
goofing off
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* strkittens | |
* | |
* Conceptually, strcat() is a sequence of strlen() followed by a | |
* strcpy() using the offset derived from strlen(). | |
* These functions build on that idea. | |
* | |
* None of the FreeBSD, OpenBSD, nor Linux/glibc implementations | |
* of strcat() use this delegation to strcpy(), presumably because | |
* the pointer-based strcpy() algorithm, when used with short strings, | |
* is sufficiently simple and efficient that an additional procedure | |
* call was considered unnecessary. | |
*/ | |
#include <cstdio> | |
#include <cstdlib> | |
#include <cstring> | |
char *strkitten(char *s1, char *s2); | |
char *charArrayKitten(char s1[], char s2[]); | |
int main() | |
{ | |
char buffer1[80] = {}; | |
char buffer2[80] = {}; | |
char *foo = "Foo"; | |
char *bar = " Bar"; | |
strkitten(buffer1, foo); // buffer1 => "Foo" | |
charArrayKitten(buffer2, foo); // buffer2 => "Foo" | |
printf("buffer1 => \"%s\"\nbuffer2 => \"%s\"\n\n", buffer1, buffer2); | |
strkitten(buffer1, bar); // buffer1 => "Foo Bar" | |
charArrayKitten(buffer2, bar); // buffer2 => "Foo Bar" | |
printf("buffer1 => \"%s\"\nbuffer2 => \"%s\"\n\n", buffer1, buffer2); | |
strkitten(buffer1, bar); // buffer1 => "Foo Bar Bar" | |
charArrayKitten(buffer2, bar); // buffer2 => "Foo Bar Bar" | |
printf("buffer1 => \"%s\"\nbuffer2 => \"%s\"\n\n", buffer1, buffer2); | |
system("pause"); | |
return (0); | |
} | |
/* | |
* Ironically, I think the pointer-based version of this function | |
* provides greater clarity of purpose. Especially given the common | |
* C idiom of "typeptr + int * sizeof(type)". | |
*/ | |
char * | |
strkitten(char *s1, char *s2) | |
{ | |
strcpy(s1 + strlen(s1), s2); | |
return s1; | |
} | |
/* | |
* Mostly to prove I could do it using array indicies. | |
* This method appears more cluttered, probably due to the | |
* additional requirement of the & operator to turn the | |
* element access back into a char*. | |
*/ | |
char * | |
charArrayKitten(char s1[], char s2[]) | |
{ | |
strcpy(&s1[strlen(s1)], s2); | |
return s1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment