您的位置:首页 > 其它

c总结2 ---自己实现字符串的拷贝(指针学习1)

2015-10-17 14:09 330 查看
我们在使用c的时候,如果要实现字符串的拷贝,可能会用到strcpy函数。那么我们能否自己实现一下呢?

我们先来看一段代码

int _tmain(int argc, _TCHAR* argv[])
{
char * p1 = "abcde";

printf("*p1++ = %c \n", *p1++ );  //a   ++在后  想当于 先将*p的值进行打印  然后*p+1
printf("*p1++ = %c \n", *p1++);   //b
printf("*p1++ = %c \n", *p1++);   //c

system("pause");
return 0;
}


我们借助指针来实现该函数

#include "stdafx.h"
#include <stdlib.h>
#include <string.h>

void myCopy(char *from, char* to)
{
//当*from为 '\0'的时候结束   每次执行语句后 *from *to自增 将指针加1
for ( ; *from != '\0'; *from++, *to++)
{
//将 *from的值赋值给*to
*to = *from;
}

//因为是字符指针 要使用'\0'结束
*to = '\0';
}

int _tmain(int argc, _TCHAR* argv[])
{
char * p1 = "abcde";
char p2[9];	//定义一个数组用来封装拷贝的数据

myCopy(p1, p2);
printf("p2 = %s \n", p2);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: