一步一步写算法(自己实现strcpy函数)

来源:互联网 发布:java中类属变量是什么 编辑:程序博客网 时间:2024/06/15 01:40

v 自己编写一个函数,实现strcopy库函数的功能。

   #include <stdio.h>void my_copy(char *i,char *j){while(*j != '\0')  //遍历字符数组b {*i = *j;      //取出数组B中的元素赋值给a i++;          //指针指向数组a的下一个地址 j++;          //指针指向数组b的下一个地址 }}int main(){char a[10] = {0};char b[10] = {0};printf("Please input the the string of b:\n");scanf("%s",b);my_copy(a,b);printf("a : %s\n",a);}

运行结果:

Please input the string of b:

hello

a : hello


程序二:

#include <stdio.h>void my_copy(char *i,char *j){while(*i++ = *j++);     //简练:同时实现取值,赋值,地址加一,三个功能 }int main(){char a[10] = {0};char b[10] = {0};printf("Please input the string of b:\n");scanf("%s",b);my_copy(a,b);printf("a : %s\n",a);return 0;}


运行结果:

Please input the string of b:

hello

a : hello

 

 

分析:从以上两个函数可以看出在my_copy函数中,语句while(*i++ = *j++); 就相当于*i = *j; i++;j++;这三句话。语句所实现的功能就是将数组b中的,每一个元素都赋值给b

那么为什么上面的一个语句就能实现这三个语句的功能呢?

 

我们首先的先了解这么一个知识点:

*p++(*p)++的区别

 

下面举个例子来说明:

Int *p,a;

P = &a;

*p = 3;

 

那么

Y = *p++即先将P地址里面保存的数据取出来,再赋值给y,最后将P的地址加一,指向下一个元素

Y = (*p)++:即先将P地址里面保存的值取出来,再赋值给Y,最后将P地址里面保存的内容加一

总结下来,区别也就是一个是地址加一,一个是地址里面保存的内容加一。并且两个语句其实都实现了三个功能。

所以,学会巧妙的使用*p++(*p)++有利于我们进一步学好算法和指针。

原创粉丝点击