C language learning summary _08_ library function simulation implementation

1. Simulated realization of strlen (string effective length):
There are three ways:
1. Calculator:

size_t my_strlen_1(const char* str)
{
    
    
	int count = 0;
	while (*str)
	{
    
    
		count++;
		str++;	
	}
	return count;
}

2. Recursive implementation

//递归
size_t my_strlen_2(const char * str)
{
    
    
	if (*str == '\0'){
    
    
		return 0;
	}
	else{
    
    
		return 1 + my_strlen_2(str + 1);
	}
}

3. Pointer minus pointer

//指针-指针的方式
size_t my_strlen_3(const char *str)
{
    
    
	const char *p = str;
	while (*p){
    
    
		p++;
	}
	return p - str;
}

Second, simulate the realization of string copy (strcpy)

char *my_strcpy(char *dest, const char* src)
{
    
    
	assert(dest && src);
	char *ret = dest;
	while (*dest = *src){
    
    
		dest++;
		src++;
	}
	return ret;
}

3. To simulate the string appending strcat, you
only need to move the dest pointer to the end and the remaining logic is the same as strcpy

/*
  三、模拟实现strcat
*/
char *my_strcat(char* dest, const char* src){
    
    
	assert(dest&&src);
	char *ret = dest;
	while (*dest){
    
    
		dest++;
	}
	while (*dest = *src){
    
    
		dest++;
		src++;
	}
	return ret;
}

Four, simulate strcmp

/*
  模拟实现strcmp
*/
int my_strcmp(const char * src, const char *dest){
    
    
	int ret = 0;
	assert(src != NULL);
	assert(dest != NULL);
	while (!(ret = *(unsigned char*)src - *(unsigned char*)dest) && *dest)
	{
    
    
		src++;
		dest++;
	}
	if (ret > 0){
    
    
		return 1;
	}
	if (ret < 0){
    
    
		return -1;
	}
	return ret;

}

Five, simulate memcpy

/* 
   模拟实现memcpy
*/
void * my_memcpy(void * dst, const void *src, size_t num)
{
    
    
	assert(dst && src);
	char *_dst = (char *)dst;
	char *_src = (const char*)src;
	while (num){
    
    
		*_dst = *_src;
		_src++;
		_dst++;
		num--;
	}
}

But memcpy can’t handle the copy of memory overlap.
Through drawing analysis, the string copy can be divided into two parts, from the low 3 address to the high address. At this time, the logic of the above memcpy will no longer meet the requirements, so it is necessary to simulate the implementation of memmove , In the earlier version of the compiler, memmove can handle memory overlap, but memcpy cannot. Memcopy is optimized in the newer compiler, and now the two functions are the same.
Six, the simulation realization of memmove

/*
   模拟实现memmove
*/
void * my_memmove(void * dst, const void *src, size_t num)
{
    
    
	assert(dst && src);
	char *_dst = (char *)dst;
	char *_src = (const char*)src;

	if (_dst > _src && _dst < _src + num)
	{
    
    
		//从右往左拷贝
		_dst = _dst + num - 1;
		_src = _src + num - 1;
		while (num){
    
    
			*_dst = *_src;
			_src--;
			_dst--;
			num--;
		}
	}
	else{
    
    
		//从左向右拷贝
		while (num){
    
    
			*_dst = *_src;
			_src++;
			_dst++;
			num--;
		}

	}
	return dst;
}

Guess you like

Origin blog.csdn.net/CZHLNN/article/details/109895200