69,381
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#define NDEBUG
#include <assert.h>
char* my_strncpy(char *strDest,const char *strSrc,int n){
assert((strDest!=NULL)&&(strSrc!=NULL));
char *address=strDest;
for(int i=0;i<n;i++)
*strDest++=*strSrc++;
*strDest='\0';
return address;
}
int main(void){
char array1[]="sdsad";
char array2[]="hello world";
char *strDest=array1;
char *strSrc=array2;
int n=5;
my_strncpy(strDest,strSrc,8);
printf("%s",strDest);
return 0;
}
代码在GCC上面跑了一遍没问题的。
但有几个细节要注意:const char ×strSrc 源地址是一个常量。第二个考点:assert断言,程序的安全性。第三个考点:为了保证链式操作 可以返回一个指针。
你比我要聪明。。我这是前几天刚看到这个问题。
还有,要注意代码的精简性,没事多看一下源码,代码应追求短小精悍。/***
*strncpy.c - copy at most n characters of string
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines strncpy() - copy at most n characters of string
*
*******************************************************************************/
#include <cruntime.h>
#include <string.h>
/***
*char *strncpy(dest, source, count) - copy at most n characters
*
*Purpose:
* Copies count characters from the source string to the
* destination. If count is less than the length of source,
* NO NULL CHARACTER is put onto the end of the copied string.
* If count is greater than the length of sources, dest is padded
* with null characters to length count.
*
*
*Entry:
* char *dest - pointer to destination
* char *source - source string for copy
* unsigned count - max number of characters to copy
*
*Exit:
* returns dest
*
*Exceptions:
*
*******************************************************************************/
char * __cdecl strncpy (
char * dest,
const char * source,
size_t count
)
{
char *start = dest;
while (count && (*dest++ = *source++)) /* copy string */
count--;
if (count) /* pad out with zeroes */
while (--count)
*dest++ = '\0';
return(start);
}
#include <stdio.h>
char *mystrncpy( char *des, const char *source, int n )
{
if( des == NULL || source == NULL )
return des;
char *tmp = des;
for( int i = 0; i < n; i++)
{
if( *source != '\0')
{
*tmp++ = *source++;
}
}
*tmp = '\0';
return des;
}
int main()
{
char s[] = "hello world!";
char *t = "boys";
printf( "%s\n", mystrncpy( s, t, 3 ) );
return 0;
}