strcat函数指针实现方式(记录自已编写strcat 函数过程中的错误和经验)

为了实现strcat函数的功能采用fgets()函数
fgets()函数模型如下
***char fgets(char s, int size, FILE stream);
我这里对fgets()函数的理解是从标准输入流中读取规定size长度的字符数填充到指定的字符串(s)中
我用代码验证了一番
在这里插入图片描述
在这里插入图片描述
可以发现fgets()函数会默认把换行符’\n’也算在标准输入流中。

#define max 1024
int main()
{
	int count=0,count1=0,i,j=0;
	char str[max],str1[max];
	printf("请依次输入两串字符串\n");
	fgets(str,max,stdin);
	fgets(str1,max,stdin);
	char *p=str;
	char *p1=str1;
	
	for(i=0;*(p+i)!='\0';i++)
	{
		 count++;
	}
	for(i=0;*(p1+i)!='\0';i++)
	{
		count1++;
	}
	for(i=count-1;j<count1;i++,j++)
	{
		*(p+i)=*(p1+j);
	}
	printf("连接后的字符串为%s",str);
	
	
	
	


}

补充:

#include <stdio.h>
#define max 1024
int main()
{
	int count,count1,i,j=0;
	char str[max],str1[max];
	printf("\n");
	fgets(str,max,stdin);
	fgets(str1,max,stdin);
	char *p=str;
	char *p1=str1;
	
	for(i=0;*(p+i)!='\0';i++)
	{
		 count++;
	}
	for(i=0;*(p1+i)!='\0';i++)
	{
		count1++;
	}
	for(i=count-1;j<count1;i++,j++)
	{
		*(p+i)=*(p1+j);
	}
	printf("连接后的字符串为%s",str);
	
	
	
	


}

错误示例会发现无法实现连接的功能原因在于虽然count,count1为与main()函数中为局部变量但是默认初始值是随机分配的。

#include <stdio.h>
#define max 1024
int main()
{			
		char str[max];
		int i; 
		printf("请输入\n");
		fgets(str,max,stdin);
		char *p=str;
		for(i=0;i<max;i++)
		{
			printf("%c ",*(p+i));
		}
		

}

在这里插入图片描述
在C语言中没有越界检查机制切记切记。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值