String Functions |
A way that works: strdup.c | The better way: strcpy.c |
---|---|
#include <stdio.h> #include <stdlib.h> char *strdupl(char *s); int main() { char *u = "abcdefghij0123456789"; char *w = strdupl(u); printf("w: \"%s\"\n", w); } char *strdupl(char *s) { char *t, *save; t = (char *)malloc(strlen(s) + 1); save = t; while (*t++ = *s++) ; return save; } |
#include <stdio.h> #include <stdlib.h> void strcpy(char *t, char *s); int main() { char *u = "abcdefghij0123456789"; char *w = (char *)malloc(strlen(u)+1); strcpy(w, u); printf("w: \"%s\"\n", w); } void strcpy(char *t, char *s) { while (*t++ = *s++) ; } |
% cc -o strdup strdup.c % strdup w: "abcdefghij0123456789" |
% cc -o strcpy strcpy.c % strcpy w: "abcdefghij0123456789" |
Both these programs use a function to create a copy of a string. On the left storage for the copy is allocated inside the strdup function. A pointer to this storage is returned from the function. The problem with this method is that the allocated storage may not later be deallocated (with free).
Instead one should use the method on the right. Here the calling function provides the storage for the copy. So it is easier for this calling function to remember to later deallocate the storage.
Using array indexes: strcmp.c | Using pointers: strcmp2.c |
---|---|
#include <stdio.h> int strcmp(char *s, char *t); int main() { printf("c1: %i\n", strcmp("xyz", "xyz")); printf("c2: %i\n", strcmp("xyw", "xyz")); printf("c3: %i\n", strcmp("xyz", "xyw")); } int strcmp(char *s, char *t) { int i = 0; while (s[i] == t[i]) { if (s[i] == '\0') return 0; i++; } return s[i] - t[i]; } |
#include <stdio.h> int strcmp2(char *s, char *t); int main() { printf("c1: %i\n", strcmp2("xyz", "xyz")); printf("c2: %i\n", strcmp2("xyw", "xyz")); printf("c3: %i\n", strcmp2("xyz", "xyw")); } int strcmp2(char *s, char *t) { while (*s == *t) { if (*s == '\0') return 0; s++; t++; } return *s - *t; } |
% cc -o strcmp strcmp.c % strcmp c1: 0 c2: -3 c3: 3 |
% cc -o strcmp2 strcmp2.c % strcmp c1: 0 c2: -3 c3: 3 |