Sams Teach Yourself C in 21 Days

(singke) #1
Enter the number of characters to copy (1-26)
15
Before strncpy destination = ..........................
After strncpy destination = abcdefghijklmno...........
In addition to demonstrating the strncpy()function, this program also illustrates
an effective way to ensure that only correct information is entered by the user.
Lines 13–20 contain a whileloop that prompts the user for a number from 1–26. The
loop continues until a valid value is entered, so the program can’t continue until the user
enters a valid value. When a number between 1 and 26 is entered, line 22 prints the origi-
nal value of dest, line 24 copies the number of characters specified by the user from
sourcetodest, and line 26 prints the final value of dest.

486 Day 17

INPUT/
OUTPUT

ANALYSIS

Be sure that the number of characters copied doesn’t exceed the allocated
size of the destination. Also, be aware that strncpy()does not add a null
terminator.

Caution


Thestrdup()Function ................................................................................

There is another string copying function worth mentioning. The strdup()function is
similar to strcpy(), except that strdup()performs its own memory allocation for the
destination string with a call to malloc(). In effect, it does what you did in Listing 17.2,
allocating space with malloc()and then calling strcpy().
You should note that strdup()is not an ANSI-standard function. It is included with
many compilers including the Microsoft, Borland, and Symantec C libraries, but it might
not be present (or it might be different) in other C compilers.
The prototype for strdup()is
char *strdup( char *source );
The argument source is a pointer to the source string. The function returns a pointer to
the destination string—the space allocated by malloc()—orNULLif the needed memory
can’t be allocated. Listing 17.4 demonstrates the use of strdup().

LISTING17.4 strdup.c. Using strdup()to copy a string with automatic memory
allocation
1: /* The non-ANSI strdup() function. */
2: #include <stdlib.h>

28 448201x-CH17 8/13/02 11:13 AM Page 486

Free download pdf