string.h中的几个函数实现

typedef unsigned int size_t; void * memcpy ( void * destination, const void * source, size_t num ) { void* ret = destination; while (num--) { *(char*) destination = *(char*) source; destination = (char*) destination + 1; source = (char*) source + 1; // void* 和 const void*不能用++自增,即使在转换成普通指针之后 } return ret; } void * memmove ( void * destination, const void * source, size_t num ) { void *ret = destination; if (source >= destination || (char*)source + num <= destination) { while (num--) { *(char*) destination = *(char*) source; destination = (char*) destination + 1; source = (char*) source + 1; } } else // 指针区域overlap的状况 { source = (char*)source + num - 1; destination = (char*)destination + num - 1; while (num--) { *(char*) destination = *(char*) source; destination = (char*) destination- 1; source = (char*) source - 1; } } return ret; } char * strcpy ( char * destination, const char * source ) { char *ret = destination; while ((*destination = *source) != '/0') { destination++; source++; } return ret; } char * strncpy ( char * destination, const char * source, size_t num ) { char *ret = destination; while (num-- && (*destination = *source) != '/0') { destination++; source++; } while (num--) { *destination++ = '/0'; } return ret; } int strcmp ( const char * str1, const char * str2 ) { int ret = 0; while ((ret = *str1 - *str2) == 0 && *str2 != '/0') { str1++; str2++; } if (ret < 0) { ret = -1; } else if (ret > 0) { ret = 1; } return ret; } int memcmp ( const void * ptr1, const void * ptr2, size_t num ) { while (num-- && *(char*)ptr1 == *(char*)ptr2) { ptr1 = (char*)ptr1 + 1; ptr2 = (char*)ptr2 + 1; } return *(char*)ptr1 - *(char*)ptr2; } char * strcat ( char * destination, const char * source ) { char *ret = destination; while (*destination++ != '/0'); while ((*destination++ = *source++) != '0'); return ret; } size_t strlen ( const char * str ) { size_t ret = 0; while (*str != '/0') { ret++; str++; } return ret; }

你可能感兴趣的:(string.h中的几个函数实现)