Last active
August 3, 2016 22:32
-
-
Save olafurjohannsson/735ad09ca9aedafc3b3e3b74c3f496ed to your computer and use it in GitHub Desktop.
C stdlib functions
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
#include "stdlib.h" | |
/* | |
* string_length: | |
* Returns the length of the pointer *s | |
* Same as strlen in <stdlib> | |
*/ | |
unsigned long string_length(const char *s) { | |
int c = 0; | |
// dereference the pointer until EOF and raise the counter variable | |
while (*s++) c++; | |
return c; | |
} | |
/* | |
* string_copy: | |
* Copies the string *src to *dst | |
* Same as strcpy in <stdlib> | |
*/ | |
void string_copy(const char *src, char *dst) { | |
while ((*dst++ = *src++) != '\0') | |
; | |
} | |
/* | |
* string_duplicate: | |
* Returns the duplicate of the string *s | |
* Same as strdup in <stdlib> | |
*/ | |
char *string_duplicate(char *s) { | |
// start by allocating enough memory for the string + '\0' | |
char *p = (char*)malloc(string_length(s) + 1); | |
// if success we copy the string | |
if (p != NULL) | |
string_copy(p, s); | |
return p; | |
} |
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
#ifndef STDLIB_H | |
#define STDLIB_H | |
extern unsigned long string_length(const char *s); | |
extern void string_copy(const char *src, char *dst); | |
extern char *string_duplicate(char *s); | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment