C常见标准库函数实现

C语言中的一些标准库函数虽然简单,但笔试面试中确常常考察.

  1. void *memchr(const void *s, int c, size_t n);
    /***
    *Description:
    *       The memchr() function locates the first occurrence of c (converted to an unsigned char) in the initial n characters (each interpreted as unsigned char) of the object pointed to by s.
    *
    *Return value:
    *       The memchr() function returns a pointer to the located character, or a null pointer if the character does not occur in the object.
    *
    */
    void *memchr(const void *s, int c, size_t n)
    {
        unsigned char *p = (unsigned char*)s;
        	while( n-- )
            if( *p != (unsigned char)c )
                		p++;
            	else
                		return p;
        	return 0;
    }
     
  2. int memcmp(const void * s1, const void * s2,size_t n);
    /***
    *Description:
    *       The memcmp() function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s2.
    Beware: Padding is indeterminate, strings need not fill their allotted space.
    *
    *Return value:
    *       The memcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.
    *
    */
    int memcmp(const void * s1, const void * s2,size_t n)
    {
        	const unsigned char *p1 = s1, *p2 = s2;
       		 while(n--)
            		if( *p1 != *p2 )
                			return *p1 - *p2;
            		else
                			p1++,p2++;
       	return 0;
    }
     
  3. void *memcpy(void *dest, const void *src, size_t n);
    /***
    *Description:
    *       The memcpy() function shall copy the first n bytes pointed to by src to the buffer pointed to by dest. Source and destination may not overlap.
    If source and destination might overlap, memmove() must be used instead.
    *
    *Return value:
    *       The memcpy() function shall return the pointer dest; the function has no failure mode and no error return.
    *
    */
    void *memcpy(void *dest, const void *src, size_t n)
    {
        	char *dp =(char *) dest;
        	const char *sp = (const char *) src;
        	while (n--)
            	*dp++ = *sp++;
        	return dest;
    }
     
  4. void *memmove(void *dest, const void *src, size_t n);
    /***
    *Description:
    *       The memmove() function shall copy the first n bytes pointed to by src to the buffer pointed to by dest. Source and *destination may overlap.
    *
    *Return value:
    *       The memmove() function shall return the pointer dest; the function has no failure mode and no error return.
    *
    */
    void *memmove(void *dest, const void *src, size_t n)
    {
        	char *tempSrc;
    	char *tempDest;
    	assert((NULL!=dest)&&(NULL!=src));
    	assert(count>0);
    	tempSrc=(char *) src;
    	tempDest=(char *) dest;
    	if(tempDest<tempSrc||tempSrc+count<tempDest)//un overloap
    	{
    		while(count--)
    			*tempDest++=*tempSrc;
    	}else                                                                              //overloap
    	{
    		while(count)
    		{
    			*(tempDest+count-1)=*(tempSrc+count-1);
    			count--;
    		}
    	}
    }
  5. void *memset(void *s, int c, size_t n);
    /***
    *Description:
    *       The memset function copies the value of c (converted to an unsigned char) into each of the first n characters of the object pointed to by s.
    *
    *Return value:
    *       The memset function returns the value of s.
    *
    */
    void *memset(void *s, int c, size_t n)
    {
        	unsigned char* p=s;
       	while(n--)
            	*p++ = (unsigned char) c;
        	return s;
    }
     
  6. char *strcat(char *dest, const char *src);
    /***
    *Description:
    *       The strcat() function shall append the null-terminated string pointed to by src to the null-terminated string pointed to by dest. The first character of src overwrites the null-terminator of dest. Source and destination may not overlap.
    *
    *Return value:
    *       The strcat() function shall return the pointer dest; the function has no failure mode and no error return.
    *
    */
    char *strcat(char *dest, const char *src)
    {
        	char *ret = dest;
       	while (*dest)
            	dest++;
        	while (*dest++ = *src++)
            ;
        	return ret;
    }
     
  7. char *strchr(const char *s, int c);
    /***
    *Description:
    *       The strchr() function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.
    *
    *Return value:
    *       The strchr() function returns a pointer to the located character, or a null pointer if the character does not occur in the string.
    *
    */
    char *strchr(const char *s, int c)
    {
        	while (*s != (char)c)
            	if (!*s++)
                		return 0;
        	return (char *)s;
    }
  8. int strcmp(const char * s1, const char * s2);
    /***
    *Description:
    *       The strcmp() function compares the string pointed to by s1 to the string pointed to by s2.
    *
    *Return value:
    *       The strcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.
    *
    */
    int strcmp(const char* s1, const char* s2)
    {
        	while(*s1 && (*s1==*s2))
            	s1++,s2++;
        	return *(const unsigned char*)s1-*(const unsigned char*)s2;
    }
     
  9. char *strcpy(char *dest, const char *src);
    /***
    *Description:
    *       The strcpy() function shall copy the null-terminated string pointed to by src to the memory pointed to by dest. Source and destination may not overlap.
    *
    *Return value:
    *       The strcpy() function shall return the pointer dest; the function has no failure mode and no error return.
    *
    */
    char *strcpy(char *dest, const char* src)
    {
        	char *ret = dest;
            while (*dest++ = *src++)
            ;
        	return ret;
    }
  10. size_t strlen(const char *s);
    /***
    *Description:
    *       The strlen() function shall compute the number of bytes in the string to which s points, not including the terminating null byte.
    *
    *Return value:
    *       The strlen() function shall return the length of s; the function has no failure mode and no error return.
    *
    */
    size_t strlen(const char *s) {
        	size_t i;
        	for (i = 0; s[i] != '\0'; i++) ;
        	return i;
    }
  11. long __cdecl atol(const char* nptr)
    /***
    *long atol(char *nptr) - Convert string to long
    *
    *Purpose:
    *       Converts ASCII string pointed to by nptr to binary.
    *       Overflow is not detected.
    *
    *Entry:
    *       nptr = ptr to string to convert
    *
    *Exit:
    *       return long int value of the string
    *
    *Exceptions:
    *       None - overflow is not detected.
    */
    long __cdecl atol(const char* nptr)
    {
           int c;              /* current char */
           long total;         /* current total */
           int sign;           /* if '-', then negative, otherwise positive */
    	/*skip whitespace*/
    	while(isspace( (int)(unsigned char) *nptr) )
    		nptr++;
    	c=(int)(unsigned char *)nptr++;
    	sign=c;
    	if(c=='-'||c=='+')
    		c=(int )(unsigned char)*nptr++;
    	total=0;
    	while(isdigit(c))
    	{
    		total=total*10+(c-'0');
    		c=(int)(unsigned char)*nptr++;
    	}
    	if(sign=='-')
    		total=-total;
    	return total;
    }
  12. char *itoa(int val, char *buf, unsigned radix)
    /***
    *Description:
    *       itoa takes the integer input value input and converts it to a number in base radix.
    *
    *Return value:
    *       The resulting number (a sequence of base-radix digits) is written to the output buffer buffer.
    *
    */
    char *itoa(int val, char *buf, unsigned radix)
    {
    	char *firstDigital;
    	char temp;
    	char *p;
    	int digital;
    	p=buf;
    	if(val<0)
    	{
    		*p++='-';
    		val=-val;
    	}
    	firstDigital=p;
    	do{
    		digital=val%radix;
    		val=val/radix;
    		if(digital>9)
    			*p=digital-10+'a';//key point
    		else
    			*p=digital+'0';
    	}while(val>0);
    	*p--='\0';
    	while(firstDigital<p)
    	{
    		temp=*p;
    		*p=*firstDigital;
    		*firstDigital=temp;
    		--p;
    		++firstDigital;
    	}
    	return buf;
    }



     
Here's an example of inline assembler code that calculates the length of a string: ```c #include <stdio.h> int main() { char str[] = "Hello, world!"; int len; asm volatile ( "movl $0, %0\n\t" // initialize counter to 0 "1:\n\t" "movb (%1), %%al\n\t" // load next character into al "cmpb $0, %%al\n\t" // compare with null terminator "je 2f\n\t" // if equal, jump to end "incl %0\n\t" // increment counter "incl %1\n\t" // increment pointer "jmp 1b\n\t" // jump to beginning of loop "2:\n\t" : "=r" (len) // output: len = counter : "r" (str) // input: str = pointer to string : "%eax" // clobbered register: eax ); printf("Length of string: %d\n", len); return 0; } ``` Explanation: - The `asm volatile` statement tells the compiler that this is inline assembler code that may modify registers and memory, and that it should not optimize or reorder instructions. - The `movl $0, %0` initializes the counter to 0 and assigns it to the output variable `len`. - The label `1:` marks the beginning of a loop that processes each character of the string. - The `movb (%1), %%al` instruction loads the next character into the `al` register. - The `cmpb $0, %%al` instruction compares the character with the null terminator. - The `je 2f` instruction jumps to the label `2:` if the character is a null terminator. - The `incl %0` instruction increments the counter. - The `incl %1` instruction increments the pointer to the next character. - The `jmp 1b` instruction jumps back to the beginning of the loop. - The label `2:` marks the end of the loop. - The output operand `=r` (len) tells the compiler that `len` is an output variable that will be stored in a register. - The input operand `"r" (str)` tells the compiler that `str` is an input variable that will be stored in a register. - The clobbered register `%eax` tells the compiler that the `eax` register may be modified by the inline assembler code.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值