strncpy(3) - Linux man page
Name
strcpy, strncpy - copy a string
Synopsis
#include <string.h> char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n);
Description
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.
If the length of src is less than n, strncpy() writes additional null bytes to dest to ensure that a total of n bytes are written.
A simple implementation of strncpy() might be:
-
char * strncpy(char *dest, const char *src, size_t n) { size_t i; for (i = 0; i < n && src[i] != '\0'; i++) dest[i] = src[i]; for ( ; i < n; i++) dest[i] = '\0'; return dest; }
Return Value
The strcpy() and strncpy() functions return a pointer to the destination string dest.
strcmp(3) - Linux man page
Name
strcmp , strncmp - compare two stringsSynopsis
#include <string.h> int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n);
Description
The strncmp() function is similar, except it only compares the first (at most) nbytes of s1 and s2.
Return Value
The strcmp () and strncmp () functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2 .Conforming to
SVr4, 4.3BSD, C89, C99.
(网上找的实现代码:不知道来源)
code:
--------------------------------------------------------------------------------
int __cdecl strcmp (const char *dst, const char *src)
{
int ret = 0 ;
while(!(ret = *(unsigned char *)dst - *(unsigned char *)src) && *src)
{
++dst;
++src;
}
if ( ret < 0 )
ret = -1 ;
else if ( ret > 0 )
ret = 1 ;
return( ret );
}
从下面几个方面阐述:
1.src和dst都为空串如何返回?
2.为什么要用unsigned char*强制转换?
3.可否用*src替换*dst作为while条件?
4.是否是multithread-safe?
5.能否用于multibyte-character strings的比较?
6.能否用更少行表达?
从下面几个方面阐述:
1.src和dst都为空串如何返回?
空串是什么?""还是NULL? src和dst都为""的话,那么返回0,如果有一个为NULL,则内存访问违例。
2.为什么要用unsigned char*强制转换?
不能.考虑src和dst是如下值:
char src[] = {0x1, 0x2, 0x3, 0};
char dst[] = {(char)0xb1, (char)0xb2, (char)0xb3, 0};
3.可否用*src替换*dst作为while条件?
可以
4.是否是multithread-safe?
是
5.能否用于multibyte-character strings的比较?
no
6.能否用更少行表达?
不要犯傻,做些没意义的事。
memset
下面来看memset的实现:(代码来自《C标准库》P398)
- void *(memset) (void *s,int c,size_t n)
- {
- const unsigned char uc = c;
- unsigned char *su;
- for(su = s;0 < n;++su,--n)
- *su = uc;
- return s;
- }
strcpy相关:http://blog.csdn.net/m6830098/article/details/8859530
memset相关:http://blog.csdn.net/hackbuteer1/article/details/7343189