去哪儿网面试总结

1. strlen

#include <iostream>
#include <cassert>
using namespace std;

int _strlen(const char *str)	// 字符串加const修饰,表明其仅为输入参数
{
	assert(str != NULL);

	int len = 0;
	while ((*str++) != '\0')
	{
		++len;
	}

	return len;
}

char* _strcat(char *strDest, const char *strSrc)	// 源字符串加const修饰,表明其仅为输入参数
{
	char *address = strDest;	// 该句放在assert之后出错

	assert((strDest!=NULL) && (strSrc!=NULL));

	while (*strDest != '\0')	// 若使用while(*strDest++),则会出错,
	{							// 因为++是不受循环约束的。所以要在循环体内++;
		++strDest;				// 因为要是*strDest最后指向该字符串的结束符标志'\0'。
	}

	while ((*strDest++ = *strSrc++) != '\0')
	{
	}

	return address;	//	为了实现链式操作,将目的地址返回。
}

char* _strcpy(char *strDest, const char *strSrc)
{
	char *address = strDest;

	assert((strDest!=NULL) && (strSrc!=NULL));

	while (*strSrc != '\0')
	{
		*strDest++ = *strSrc++;
	}

	*strDest = '\0';

	return address;
}

int _strcmp(const char *pStr1, const char *pStr2)
{
	assert((pStr1!='\0') && (pStr2!='\0'));

	while ((*pStr1!='\0') && (*pStr2!='\0') && (*pStr1==*pStr2))
	{
		++pStr1;
		++pStr2;
	}

	return (*pStr1 - *pStr2);
}

void* _memcpy(void *strDest, const void *strSrc, int count)
{
	if (NULL==strDest || NULL==strSrc || count<=0)
	{
		return NULL;
	}

	unsigned char *tempDest = (unsigned char *)strDest;
	unsigned char *tempSrc = (unsigned char *)strSrc;

	while (count--)
	{
		*tempDest++ = *tempSrc++;
	}

	return strDest;
}

void* _memmove(void *dest, void *src, int n)
{
	if (NULL==dest || NULL==src || n<=0)
	{
		return NULL;
	}

	unsigned char *tempDest = (unsigned char *)dest;
	unsigned char *tempSrc = (unsigned char *)src;

	if (tempDest<=src || tempDest+n>=src)
	{
		while (n--)
		{
			*tempDest++ = *tempSrc++;

		}

	}
	else
	{
		tempDest = tempDest + n;
		tempSrc = tempSrc + n;
		while (n--)
		{
			*tempDest-- = *tempSrc--;

		}
	}

	return dest;
}

int main()
{
	char str1[100] = "lungfei";
	char str2[100] = "11111gfe";
	int a[100] = {1, 3, 5, 7, 9};
	int b[100] = {2, 4, 6, 8, 10};

	char *str = (char*)_memmove(str1, str2, 4);
	int *c = (int *)memmove(a, b, 3);
	
	for (int i=0; i<5; ++i)
	{
		cout<<c[i]<<endl;
	}

	system("pause");
	return 0;
}


2.  new和malloc的区别

你可能感兴趣的:(去哪儿网面试总结)