请教,strncpy 的应用问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 06:47:53
pt所指的内存内容为“ti3 a=123 b=456”
使用命令strncpy((arc+count_arc)->word,pt,3);
arc+count_arc)->word 所显示的内容为“ti3屯屯屯屯屯屯...”
word我定义的是char[5]
这是为什么,怎样改呢

先来一个memset((arc+count_arc)->word, 0, 5);
就可以了

先把内存清空,就不会出错!

word后面还要添加'\0'

仔细看strncpy的介绍:
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.

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() pads the remainder of
dest with null bytes.