模拟实现strcpy

来源:互联网 发布:白金网络加速器下载 编辑:程序博客网 时间:2024/05/22 12:32
  1. #include <stdio.h>  
  2. #include<assert.h>  
  3.   
  4. char *my_strncpy(char *dest, const char* src, int n)  
  5. {  
  6.     assert(dest != NULL);  
  7.     assert(src != NULL);  
  8.     char*ret = dest;  
  9.     while (n)         //复制n个字符,循环n次  
  10.     {  
  11.         *dest++ = *src++;  
  12.         n--;  
  13.     }  
  14.     if (*(dest- 1) != '\0')//判断是否已经将‘\0’复制到目标字符串中  
  15.         *dest = '\0';      //若没有则给目标字符串最后添加‘\0’   
  16.     return ret;  
  17. }  
  18. int main()  
  19. {  
  20.     char*p = "abcd";  
  21.     char q[5];  
  22.     printf("%s\n", my_strncpy(q, p,2));  
  23.     system("pause");  
  24.     return 0;  
  25. }