二、库函数模拟实现
2.1 模拟实现strlen
方法一
int my_strlen ( const char * str ) { int count = 0 ; while ( * str ) { count ++ ; str ++ ; } return count ; }
方法二
int my_strlen ( char * s ) { char * p = s ; while ( * p != ‘\0’ ) p ++ ; return p - s ; }
2.2 模拟实现strcpy
char * my_strcpy ( char * dest , const char* src ) { char * ret = dest ; assert ( dest != NULL ); // 使用时包含头文件assert.h,用于中止程序执行(如果使用空指针作为属性进行调用) assert ( src != NULL ); while (( * dest ++ = * src ++ )) { ; } return ret ; }
2.3 模拟实现strcat
char * my_strcat ( char * dest , const char* src ) { char * ret = dest ; assert ( dest != NULL ); assert ( src != NULL ); while ( * dest ) { dest ++ ; } while (( * dest ++ = * src ++ )) { ; } return ret ; }
2.4 模拟实现strstr
char * strstr ( const char * str1 , const char * str2 ) { char * cp = ( char * ) str1 ; char * s1 , * s2 ; if ( !* str2 ) return (( char * ) str1 ); while ( * cp ) { s1 = cp ; s2 = ( char * ) str2 ; while ( * s1 && * s2 && ! ( * s1 -* s2 ) ) s1 ++ , s2 ++ ; if ( !* s2 ) return ( cp ); cp ++ ; } return ( NULL );
2.5 模拟实现strcmp
int my_strcmp ( const char * src , const char * dst ) { int ret = 0 ; assert ( src != NULL ); assert ( dest != NULL ); while ( ! ( ret = * ( unsigned char * ) src - * ( unsigned char * ) dst ) && * dst ) ++ src , ++ dst ; if ( ret < 0 ) ret = - 1 ; else if ( ret > 0 ) ret = 1 ; return ( ret ); }
2.6 模拟实现memcpy
void * memcpy ( void * dst , const void * src , size_t count ) { void * ret = dst ; assert ( dst ); assert ( src ); /* *从较低地址复制到较高地址 */ while ( count -- ) { * ( char * ) dst = * ( char * ) src ; dst = ( char * ) dst + 1 ; src = ( char * ) src + 1 ; } return ( ret ); }
2.7 模拟实现memmove
void* my_memmove(void* dest,void* str, size_t num) { void* ret = dest; assert(dest && str); //从低地址复制到高地址(前—>后) if (dest<str) { while (num--) { //*dest、*str类型不确定(char*)强制转化为(最小的地址空间) *(char*)dest = *(char*)str; dest = (char*)dest+1; str = (char*)str+1; } } else//从高地址复制到低地址(后—>前) { while (num--) { *((char*)dest + num) = *((char*)str + num); } } return ret; }