用字符数组作参数
例 1. 用函数调用实现字符串的复制
#include <stdio.h>
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 .
string b= I am a teacher .
(2) 形参用字符指针变量
#include <stdio.h>
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)
{ 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′);
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69914734/viewspace-2654989/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/69914734/viewspace-2654989/