Sams Teach Yourself C in 21 Days

(singke) #1
Manipulating Strings 483

17


This program does little more than demonstrate the use of strlen(). Lines 13
and 14 display a message and get a string called buf. Line 16 uses strlen()to
assign the length of bufto the variable length. Line 18 checks whether the string was
blank by checking for a length of 0. If the string is not blank, line 19 prints the string’s
size.

Copying Strings ..................................................................................................


The C library has two functions for copying strings. Because of the way C handles
strings, you can’t simply assign one string to another, as you can in some other computer
languages. You must copy the source string from its location in memory to the memory
location of the destination string. The string-copying functions are strcpy()and
strncpy(). These functions require the header file string.h.

Thestrcpy()Function ................................................................................

The library function strcpy()copies an entire string to another memory location. Its
prototype is as follows:
char *strcpy( char *destination, const char *source );
The function strcpy()copies the string (including the terminating null character \0)
pointed to by sourceto the location pointed to by destination. The return value is a
pointer to the new string,destination.
When using strcpy(), you must first allocate storage space for the destination string.
The function has no way of knowing whether destinationpoints to allocated space. If
space hasn’t been allocated, the function overwrites strlen(source)bytes of memory,
starting at destination. This can cause unpredictable problems. The use of strcpy()is
illustrated in Listing 17.2.

ANALYSIS

When a program uses malloc()to allocate memory, as Listing 17.2 does,
good programming practice requires the use of the free()function to free
up the memory when the program is finished with it. You’ll learn about
free()on Day 20, “Working with Memory.”

Note


LISTING17.2 strcpy.c. Before using strcpy(), you must allocate storage space for the
destination string
1: /* Demonstrates strcpy(). */
2: #include <stdlib.h>
3: #include <stdio.h>

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

Free download pdf