Question 13.2

Why does strncpy not always place a '\0' terminator in the destination string?


strncpy was first designed to handle a now-obsolete data structure, the fixed-length, not-necessarily-\0-terminated ``string.'' (A related quirk of strncpy's is that it pads short strings with multiple \0's, out to the specified length.) strncpy is admittedly a bit cumbersome to use in other contexts, since you must often append a '\0' to the destination string by hand. You can get around the problem by using strncat instead of strncpy: if the destination string starts out empty, strncat does what you probably wanted strncpy to do. Another possibility is sprintf(dest, "%.*s", n, source) .

When arbitrary bytes (as opposed to strings) are being copied, memcpy is usually a more appropriate routine to use than strncpy.


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback