m½Z said:
I am a C programming beginner...
I wonder, why strncpy(s, t, n) does not put '\0' at the end of the string.
Because when I output the copied string, it output more than what I want,
until I put '\0' at the end by myself.
But, sometime I don't need put '\0' and it work well??
Like
strncpy(s, t, n);
strcat(s, t1);
....
work just what I want.
Thats just the way it works. If count is less than the length of the
source string then you must null terminate yourself with:
dest_str[count]='\0';
If count is greater than the length of the source string then the
destination string will be padded with 0s up to count. But you can still
do the dest_str[count]='\0' (it is just redundant in this case).
strncpy() is useful for ensuring that you never exceed the length of a
string (causing a crash), and you should always use it if the source string
could be longer than the destination string (or if you are not sure). If
the source string was longer then the destination string will not be
automatically null terminated so you should put a '\0' at the end yourself
as follows:
strncpy(dest_str,source_str,MAX_LEN_OF_DEST_STR);
dest_str[MAX_LEN_OF_DEST_STR]='\0';
If the source string was shorter that the destination string, the dest str
will already be NULL terminated and the second line will be redudant (but so
what!).
NOTE that _memccpy(dest,source,0,count) is equivalent to
strncpy(dest,source,count) but is generally much faster (at least on a
Windows platform compiling with Borland or Microsoft compilers).
Hope this helps...
Sean