Using C language to simulate the realization of library function strlen


Analog implementation library function strlen
★To simulate and implement strlen function, we must first know what is the function of strlen function? What is its function prototype?

The role of the strlen function is only the work of a counter. It starts counting from a certain position in memory (it can be the beginning of the string, a certain position in the middle, or even an indeterminate memory area) until it hits the first until the end of the string '\0', and then return the counter value (the length does not contain '\0').

●The following is the prototype of the strlen function in MSDN:

Now, start to simulate the implementation of the function strlen, the following is the reference code:
int my_strlen(const char *str)
{
	int count = 0;
	assert(str != NULL);//Assert, the pointer is null, print out the error message
	while (*str++)//Stop when encountering '\0', not counting '\0'
	{
		count++;
	}
	return count;
}

Let's try a test file:
#include<stdio.h>
#include<assert.h>
#include<windows.h>

intmain()
{
	int len ​​= 0;
	char *p = "abcdef";
	len = my_strlen (p);
	printf("len=%d\n", len);
	system("pause");
	return 0;
}
Full code move --> my_strcpy

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324700386&siteId=291194637