C语言的那些小秘密之指针(三)

发表于:2011-9-27 10:17

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:bigloomy(CSDNblog)    来源:51Testing软件测试网采编

  在此我也给出一种结合逗号表达式和for循环语句来实现的参考代码:

#include <stdio.h>

void copy_string(char *from,char *to)
{
 int i=0;
 for(;*to=*from,*from!='\0';from++,to++);
  
 return ;
}

int main()
{
 char str[]="this is a string!";
 printf("%s\n",str);
 char dec_str[206];
 copy_string(str,dec_str);
 printf("%s\n",dec_str);
 return 0;
}

  运行结果为:

  代码的巧妙之处在于结合了逗号表达式和for循环语句来实现,因为逗号表达式的结果为最后一个表达式的结果,所以执行判断语句里边的逗号表达式时其所取的值依然为*from!='\0'。

  有兴趣的读者自己可以尝试下其他的实现方法,下面再给出几种很巧妙的实现方法,有兴趣的读者可以自己研究下其实现原理,均为完整代码。

#include <stdio.h>

void copy_string(char *from,char *to)
{
 int i=0;
 for(;*to++=*from++;);
  
 return ;
}

int main()
{
 char str[]="this is a string!";
 printf("%s\n",str);
 char dec_str[206];
 copy_string(str,dec_str);
 printf("%s\n",dec_str);
 return 0;
}

 

#include <stdio.h>

void copy_string(char *from,char *to)
{
 int i=0;
 while(*to++=*from++);
  
 return ;
}

int main()
{
 char str[]="this is a string!";
 printf("%s\n",str);
 char dec_str[206];
 copy_string(str,dec_str);
 printf("%s\n",dec_str);
 return 0;
}

43/4<1234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号