C语言,不用strcat,设计一个函数,将两个字符数组连接起来(要用指针的办法)

#include<stdio.h>
void main()
{
void lian(char a[],char b[]);
char str1[]="hello";
char str2[]="girl";
char * p1=str1,*b=str2;
void lian(p1,p2);
printf("str1+str2:%s\n",p1);
}
void lian(char * a,char * b)
{ int i=0;
int j=0;
while(* (a+i)!='\0')
{i++;}
for(;* (b+j)!='\0';i++,j++)
{* (a+i)=* (b+j);
* (a+i+1)='\0';
}
}
我这个为什么不行

#include<stdio.h>
void lian(char *a,char *b);
void main()
{

char str1[]="hello";
char str2[]="girl";
char *p1=str1,*p2=str2;
lian(p1,p2);
printf("str1+str2:%s\n",p1);
}
void lian(char *a,char *b)
{ int i=0;
int j=0;
while(* (a+i)!='\0')
{i++;}
for(;* (b+j)!='\0';i++,j++)
{* (a+i)=* (b+j);
* (a+i+1)='\0';
}
}
你应该改这样,不过你样会有内存泄露
最好把char *p1=str1,*p2=str2;改为
char *p2=str2;
char p1[100];//给他足够大的空间
strcpy(p1,str1);//把str1赋给p1的指向,还有要加上string.h这个头文件追问

哦,谢谢你的解答,关于改char p1[100];我还是不太会,能不能帮忙改了以后发一下,谢谢

追答

#include
void lian(char *a,char *b);
void main()
{

char str1[]="hello";
char str2[]="girl";
char *p1=str1,*p2=str2;
lian(p1,p2);
printf("str1+str2:%s\n",p1);
}
void lian(char *a,char *b)
{ int i=0;
int j=0;
while(* (a+i)!='\0')
{i++;}
for(;* (b+j)!='\0';i++,j++)
{* (a+i)=* (b+j);
* (a+i+1)='\0';
}
}
你先这样运行一下,你会发现有一个报错的, 那是因为内存泄露
#include
#include
void lian(char *a,char *b);
void main()
{

char str1[]="hello";
char str2[]="girl";
char *p2=str2;
char *p2=str2;
char p1[100];
strcpy(p1,str1);
lian(p1,p2);
printf("str1+str2:%s\n",p1);
}
void lian(char *a,char *b)
{ int i=0;
int j=0;
while(* (a+i)!='\0')
{i++;}
for(;* (b+j)!='\0';i++,j++)
{* (a+i)=* (b+j);
* (a+i+1)='\0';
}
}
这样就没有问题的

温馨提示:答案为网友推荐,仅供参考
相似回答