C语言 [指针] 用函数调用实现字符串的复制(字符型指针)

解题思路:定义一个函数copy_string 用来实现字符串复制的功能,在主函数中调用此函数,函数的形参和实参可以分别用字符数组名或字符指针变量

(1)用字符数组名作为函数参数

#include <stdio.h>
int main()
{
void copy_string(char from[],char to[]);
char a[] = "I am a teacher.";
char b[] = "You are a student.";
printf("string a=%s\nstring b=%s\n", a, b); 
printf("copy string a to string b:\n");
copy_string(a, b);
printf("\nstring a= %s\nstring b=%s\n", a, b);
return 0;
}
void copy_string(char from[], char to[])
{
	int i = 0;
	while (from[i] != '\0')
	{
		to[i] = from[i];
		i++;
	}
	to[i] = '\0';
}

(2)用字符型指针变量作实参
 

#include<stdio.h>
int main()
{
	void copy_string(char from[], char to[]);
	char a[] = "I am a teacher.";
	char b[] = "You are a student."; 
	char* from = a, * to = b;
	printf("string a= %s\nstring b=%s\n",a, b); 
	printf("\ncopy string a to string b: \n");
	copy_string(from, to);//字符型指针变量作品作实参
	printf("string a=%s\nstring b=%s\n", a, b);
	return 0;
}
void copy_string(char from[], char to[])
{
	int i = 0;
	while (from[i] != '\0')
	{
		to[i] = from[i];
		i++;
	}
	to[i] = '\0';
}

程序分析:指针变量from的值是a数组首元素的地址,指针变量to的值是b数组首元素的地址。它们作为实参,把a数组首元素的地址和b数组首元素的地址传递给形参数组名from和 to(它们实质上也是指针变量),其他与程序(1)相同。
 

(3)用字符指针变量作形参和实参

#include<stdio.h>
int main()
{
	void copy_string(char* from, char* to);
	char* a = "I am a teacher.";
	char b[] = "You are a student.";//定义b为字符数组
	char* p = b;
	printf("string a=%s\nstring b=%s\n", a, b);
	printf("\ncopy string a to string b: \n");
	copy_string(a, p);//通过p改变b
	printf("string a=%s\nstring b=%s\n", a, b);
	return 0;
}
void copy_string(char* from, char* to)
{
	for (; *from != '\0'; from++, to++)
	{
		*to = *from;
	}
	*to = '\0';
}

程序改进:

(1)将copy_string函数改写为

void copy_string(char * from,char * to)

{while (( * to= * from)!='\0')

{to++;from++;}

这是先赋值后判断,免去了最后还要给*to赋空字符额外的一步。

(2) copy_string函数的函数体还可改为

{ while (( * to++= * from++)!='\0') ;}
将++放在了一起,即赋值判断后再各自++

或者写成:{while ( * from!='\0')
*to++=* from++;

* to='\0'; }

(3)由于字符可以用其ASCII 码来代替(例如,“ch='a'”可用“ch= 97”代替,“while(ch!='a')”可以用“while(ch!=97)因此,“while( * from!='\0')”可以用‘while( * from! =0)”代替('\0'的ASCII代码
而关系表达式“*from!=0”又可简化为*from”,这是因为* from的值不等于0,则表达式“* from”为真,同时“ * from!=0”也为真。因此“while( * from!=0)”和“while(* from)”是等价的。所以函数体可简化为

{ while ( * from)
* to++= * from++;

*to='\0’;
}
以上的while语句还等价于:while(*to++=*from++)

等价于:while((*to++=*from++)!='\0')

(4)也可以用字符数组名作函数形参,在函数中另定义两个指针变量pl,p2。函数copy_string可写为:

void copy_string(char from[],char to[])

{

char * p1,* p2;
pl=from; p2=to;
while(( * p2++=* p1++)!='\0');

}
 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值