在主函数中,首先定义两个字符数组,分别存放字符串" Long love"和“China”;然后用指针变量作为函数参数,调用自编的字符串连接函数(函数名为 str _ cat ,函数参数为两个字符指针变量),将两个字符串进行连接;最后通过
printf 函数,使用% s 格式符将连接后的字符串输出。
注释的地方是关键点
char* str_cat(char *s1, char *s2){
int l1=0, l2=0, i=0;
char *p = s1;
while(*(p++)!='\0') l1++; //s1长度
p = s2;
while(*(p++)!='\0') l2++; //s2长度
p = (char*)malloc((l1+l2+1)*sizeof(char)); //申请内存
while(*s1!='\0') p[i++]=*(s1++); //拷贝s1
while(*s2!='\0') p[i++]=*(s2++); //拷贝s2
p[i]='\0'; //字符串结束符
return p;
}
int main() {
char s1[]="Long love";
char s2[]="China";
char *p = str_cat(s1, s2);
printf("%s\n", p);
free(p); //释放内存
return 0;
}