赞
踩
c语言之strcpy函数使用和实现
原型:
char *strcpy(char * destination, const char *source );
strcpy是覆盖拷贝,将source全覆盖拷贝到destination,会把’\0’也拷过去,estination的空间必须>=source的空间
#include<stdio.h>
#include<string.h>
int main()
{
char p1[] = "abcde";
char* p2 = "hello";
strcpy(p1, p2);
printf("%s\n", p1);
printf("%s\n", p2);
return 0;
}
执行
# gcc strcpy.c -o strcpy
# ./strcpy
hello
hello
#include<stdio.h> #include<string.h> void stringcpy(char* char1 , const char *char2){ while(*char2){ *char1 = *char2; char1++; char2++; //验证添加char1 = '\0'; if(*char2=='\0'){ printf("退出while循环,不执行*char1 = *char2; 没有赋值给char1结束符"); printf("\n"); } } *char1 = '\0';//添加char1 = '\0'; } int main() { char str1[5] = "abcde"; const char* p = "hello"; stringcpy(str1, p); printf("%s\n", str1); printf("%s\n", p); return 0; }
执行
$ gcc strcpy.c -o strcpy
$ ./strcpy
退出while循环,不执行*char1 = *char2; 没有赋值给char1结束符
hello
hello
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。