【问题描述】
在Linux-2.6.23中strncpy的函数原型如下:
Linux-2.6.23/lib/string.h(line110-134) /** * strncpy - Copy a length-limited, %NUL-terminated string * @dest: Where to copy the string to * @src: Where to copy the string from * @count: The maximum number of bytes to copy * * The result is not %NUL-terminated if the source exceeds * @count bytes. * * In the case where the length of @src is less than that of * count, the remainder of @dest will be padded with %NUL. * */ char *strncpy(char *dest, const char *src, size_t count) { char *tmp = dest; while (count) { if ((*tmp = *src) != 0) src++; tmp++; count--; } return dest; }(1) 为什么要使用*tmp?
(2)
if ((*tmp = *src) != 0) src++; tmp++;为什么不写成:
if ((*tmp++ = *src++) != 0) ;(3) 使用strncpy该注意些什么?
【解析】
(1) 为什么要使用*tmp?
这样返回的指针是指向起始地址。
(2)
如果将
if ((*tmp = *src) != 0) src++; tmp++;改写成:
if ((*tmp++ = *src++) != 0) ;试想一下,如果src的长度小于count会发生什么?
当src的长度大于等于count时,不会出现什么问题。当src的长度小于count时,src会继续执行*src++,指针指向超出了src的地址范围,其结果是未知的。
(3)
当src的长度小于count时,dest会添加NUL('\0')字符。当src的长度大于或等于count,dest就不会添加NUL,这样就不符合字符串的定义。因此,程序设置的count值要比dest的大小至少小1,这样就可以将空字符放在数组的最后一个元素里,例如:
strncpy(dest,src,TAGSIZE-1); dest[TAGSIZE-1] = '\0';其中TAGSIZE是dest的大小。