编号及代码:
/*
*Copyright 2014(c)计算机与控制工程学院
*All rights reserved
*作者:范星月
*完成日期:2014年12月16日
*版本号v1.0
*
*问题描述:用指针变量操作字符串数组,将str2保存在str1中
*问题输入:无
*问题输出:输出数组
*/
#include <iostream>
using namespace std;
char *astrcat(char str1[], const char str2[]);
int main()
{
char s1[50]="Hello world. ";
char s2[50]="Good morning. ";
char s3[50]="vegetable bird! ";
astrcat(s1,s2);
cout<<"连接后:"<<s1<<endl;
cout<<"连接后:"<<astrcat(s2,s3)<<endl; //返回值为char*型,可以直接显示
return 0;
}
//作为示例,本函数采用了形参为数组,在实现中,直接用下标法进行访问
//实际上,在实现中,完全可以用指针法访问
char *astrcat(char str1[], const char str2[])
{
int i,j;
//请理解:以下所有str1[i]可以替换为*(str1+i),str2[j]可以……
for(i=0; str1[i]!='\0'; i++); //找到str1的结束
for(j=0; str2[j]!='\0'; i++,j++)
{
str1[i]=str2[j];
}
str1[i]='\0';//切记!!
return str1;
}
运行结果:
学习总结:
a[i]=p[i]=*(a+i)=*(p+i)=a[i]中的数据
&a[i]=p+i=a+i=a[i]的地址
学习心得:加油