C语言字符串拷贝利用指针操作,要清楚知道指针的指向
代码如下:
#include <stdio.h>
#include <assert.h>
#include <string.h> char* my_strcpy1(char* dest, const char* src)
{
assert(dest != NULL && src != NULL);
char* ret = dest;
while((*dest++ = *src++) != '\0');
return ret;
}
//较第一种效率高
char* my_strcpy2(char* dest, const char* src)
{
assert(dest != NULL && src != NULL);
char* s = (char*) src;
//int delt = dest - src; //不兼容64位系统
long delt = dest - src;
while((s[delt] = *s++) != '\0');
return dest;
} int main(void)
{
char str1[];
char str2[];
char str3[]; strcpy(str1,"sam");
my_strcpy1(str2,"sam");
my_strcpy2(str3,"sam"); printf("str1 = %s\n", str1);
printf("str1 = %s\n", str2);
printf("str1 = %s\n", str3); return ;
}