字符串函数,内存函数,数据在内存中的存储 练习题

第一题(判断系统大小端) 

int main()
{
	int a = 1;
	char* p = (char*)&a;
	if (*p == 0)
	printf("为大端");
	if (*p == 1)
		printf("为小端");
}

第二题 (strncpy模拟)

char* my_strncpy(char* str1, const char* str2, size_t num)
{
	char* str3 = str1;
	size_t a = strlen(str2);
	int b = 0;

	if (num <=a)
	{
		while (b <num)
		{
			*str1++ = *str2++;
			b++;
		}
	}
	b = 0;
	if (num > a)
	{
		while (b < a + 1)
		{
			*str1 = *str2;
			if (*str1)
			{
				str1++;
				str2++;
			}
			b++;
		}
		int c = 0;
		while (c < num - a - 1)
		{
			str1++;
			*str1 = 0;
			c++;
		}
			
	}
	return  str3;
  }

 这里说下strncpy的作用。

成功模拟出来了strncpy,其作用一模一样。

第三题(strncat模拟) 

char* my_strncat(char* str1, const char* str2, size_t num)
{
	char* str3 = str1;
	size_t a = strlen(str2);
	int b = 0;
    while(*str1)
	{
		str1++;
	}
	if (num <=a)
	{
		while (b <num)
		{
			*str1++ = *str2++;
			b++;
		}
		str1++;
		*str1 = 0;
	}
	b = 0;
	if (num > a)
	{
		while (b < a + 1)
		{
			*str1 = *str2;
			if (*str1)
			{
				str1++;
				str2++;
			}
			b++;
		}	
	}
	return  str3;
  }

 

 

 成功模拟出来了strncat,其作用一模一样

第四题 (模拟memcpy函数)

void* my_memcpy(void* str1, const void* str2, size_t num)
{
	char* a = (char*)str1;
	char* b = (char*)str2;

	int c = 0;

	while (c < num)
	{
		*a = *b;
		if (*a || c != num - 1)
		{
			a++;
			b++;
		}
		c++;

	}
	return str1;
}

模拟出一模一样的memcpy函数 

第五题(模拟memmove函数) 

void* my_memmove(void* str1, const void* str2,size_t num)
{
	char* a = (char*)str1;
	char* b = (char*)str2;
	if (b >= a)
	{
		int c = 0;

		while (c < num)
		{
			*a = *b;
			if (*a||c!=num-1)
			{
				a++;
				b++;
			}
			c++;
		}
	}
	if (b < a)
	{

		num--;
		int c = 0;
		while (num)
		{
			*(a + num) = *(b + num);
		
			num--;
		}
		
	}
	return  str1;
}

 

根据其调试测试出,模拟出的函数memmove打印出的值跟库函数里的memmove一模一样。 所以该memmove模拟成功。

 额外想说的

对于漏掉的strtok函数,strerror函数 函数太过复杂,所以就不模拟了。

而strncmp ,memset,memcmp函数太过简单,就没必要模拟了 

第七题 

 

printf打印char类型是将其转化为4个字节的类型打印的,所以造成有前后不同。 

这题涉及到了整数在内存中的存储以及整数在内存中的具体细节计算。 

 第八题

 

 这题涉及到了整数在内存中的存储以及整数在内存中的具体细节计算。跟前面一题一样。

这题作者本人算错了,答案选c,解析如上。很好的一题,建议画内存格子图 

 

再说一点当我们为signed char类型时 补码为10000000时 原码值为-128,这个为-128看起来不符合其规律,的确,这是特殊规定,我们只需要记住,所以其signed char范围为-128-127。

  • 17
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值