首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

物联网学习教程—字符指针作函数参数

用字符数组作参数

例1. 用函数调用实现字符串的复制

#include

void main()

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

char a[ ]=″I am a teacher.″;

char b[ ]=″you are a student.″;

printf(“string a=%s\n string 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);

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

{ int i=0;

while(from[i]!=′\0′)

{to[i]=from[i];i++;}

to[i]=′\0′;

程序运行结果如下:

string a=I am a teacher.

string b =you are a student.

copy string a to string b:

string a =I am a teacher.

stringb=I am a teacher.

(2) 形参用字符指针变量

#include

void 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);

void copy_string(char *from,char *to)

{ for(;*from!=′\0′;from++,to++)

*to=from;

*to=′\0′;

(3) 对copy string 函数还可作简化

1、将copy_string函数改写为

void copy_string (char *from,char *to)

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

{to++;from++;}

• copy_string函数的函数体还可改为

while((*to++=*from++)!=′\0′);

•copy_string函数的函数体还可写成

{

while(*from!=′\0′)

*to++=*from++;

*to=′\0′;

•上面的while语句还可以进一步简化为下面的while语句:

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

它与下面语句等价:

while((*to++=*from++)!=′\0′);

将*from赋给*to,如果赋值后的*to值等于′\0′则循环终止(′\0′已赋给*to)

•函数体中while语句也可以改用for语句:

for(;(*to++=*from++)!=0;);

for(;*to++=*from++;);

•也可用指针变量,函数copy_string可写为

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

{char*p1,*p2;

p1=from;p2=to;

while((*p2++=*p1++)!=′\0′);

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20190826A0EOGY00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券