C语言常见面试题

1. 请实现一个itoa函数:

char* myitoa(int value, char* str, int radix)
{
	const char chvalue[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	char tmp;
	unsigned int uvalue;
	int index1 = 0, index2 = 0;
	if (radix < 2 || radix > 36)
	{
		return NULL;
	}

	if (value < 0 && radix == 10)
	{
		uvalue = -value;
		str[index1++] = '-';
	}
	else
	{
		uvalue = value;
	}

	do{
		str[index1++] = chvalue[uvalue % radix];
		uvalue /= radix;
	} while (uvalue);
	str[index1] = '\0';

	index1--;
	if (str[0] == '-') index2 = 1;
	while (index2 < index1)
	{
		tmp = str[index2];
		str[index2] = str[index1];
		str[index1] = tmp;
		index2++, index1--;
	}

	return str;
}

注意函数应该支持多种进制转换,不支持时返回值设置为NULL。


2. 请实现一个strcpy函数:

char *mystrcpy(char *dst, const char* src)
{
	char* dststart = dst;
	const char* srcend = NULL;
	char *dstend = NULL;
	size_t len = 0;

	if (NULL == dst || NULL == src)
	{
		return NULL;
	}


	if (dst > src)
	{
		len = strlen(src);
		srcend = src + len;
		dstend = dst + len;
		while (srcend != src - 1)
		{
			*dstend-- = *srcend--;
		}
	}
	else
	{
		while ((*dst++ = *src++) != '\0');
	}

	return dststart;

}

注意,返回值为目标地址的起始地址,以便支持strlen(strcpy());这样的链式表达式;

           在目标地址在源地址之后时,要从后往前拷贝字符串,以防目标地址和源字符串地址有重叠。
           和此题相似的还有一题为实现一个高质量的memcpy函数,此时可以用一次拷贝一个int的办法以减少拷贝次数。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值