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

mac2026-04-03  4

为了实现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语言中没有越界检查机制切记切记。

最新回复(0)