<<用字符指针指向一个字符串:
#include <studio.h>
void main()
{
char *string="hello,world!";
printf("%s\n",string );
return;
}
例子:将字符串a复制成字符串b
#include <studio.h>
void main()
{
char a[]="i am a boy",b[20];
int i;
for (i=0;*(a+i)!=‘\0‘;i++)
{
*(b+i)=*(a+i);
*(b+i)=‘\0‘;
printf("string a is :%s\n",a);
printf("string b is :");
for (i=0;b[i]!=‘\0‘;i++)
{
printf("%c",b[i]);
printf("\n");
}
}
}
>>使用指针变量;
#include <studio.h>
void main()
{
char a[]="i am a boy",b[20],*p1,*p2;
int i;
p1=a;p2=b;
for (;*p1!=‘\0‘;p1++,p2++)
{
*p2=*p1;
*p2=‘\0‘;
printf("string a is :%s\n",a);
printf("string b is :");
}
for (i=0;b[i]!=‘\0‘;i++)
{
printf("%c",b[i]);
printf("\n");
}
return 0;
}
程序必须保证使p1和p2同步移动;
字符指针作函数参数
将一个字符串从一个函数传递到另一个函数,可以用地址传递的方法,即用字符数组名作参数,也可以用指向字符的指针变量做参数,在被调用的函数中可以改变字符串的内容,在主调函数中可以得到改变了的字符串。
用函数调用实现字符串的复制
(1)用字符数组作参数
#include <studio.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\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;
}
void copy_string(char from[],char to[])
{
int i=0;
while (from[i]!=‘\0‘)
{
to[i]=from[i];
i++;
to[i]=‘\0‘;
}
}
>>用字符指针变量作实参,先使指针变量a和b分别指向两个字符串;
#include <studio.h>
void main()
{
void copy_string(char from[],char to[]);
char from[]="i am a teacher";
char to[]="you are a student.";
char *a=from;
char *b=to;
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;
}
void copy_string(char from[],char to[])
{
int i=0;
while(from[i]!=‘\0‘)
to[i]=from[i];
i++;
to[i]=‘\0‘;
}
>>形参用字符指针变量
#include <studio.h>
void main()
{
void copy_string(char *from,char *to);
char from[]="i am a teacher";
char to[]="you are a student.";
char *a=from;
char *b=to;
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;
}
void copy_string(char *from,char *to)
{
for (;*from!=‘\0‘;from++;to++)
{
*to=*from;
*to=‘\0‘;
}
}