Sams Teach Yourself C in 21 Days

(singke) #1
the value 99 , but you could initialize all array elements to the value 0 .memset()will be
demonstrated in Listing 20.6.

Copying Memory with the memcpy()Function ............................................

memcpy()copies bytes of data between memory blocks, sometimes called buffers. This
function doesn’t care about the type of data being copied—it simply makes an exact
byte-for-byte copy. The function prototype is
void *memcpy(void *dest, void *src, size_t count);
The arguments destandsrcpoint to the destination and source memory blocks, respec-
tively. countspecifies the number of bytes to be copied. The return value is dest. If the
two blocks of memory overlap, the function might not operate properly—some of the
data in srcmight be overwritten before being copied. Use the memmove()function, dis-
cussed next, to handle overlapping memory blocks. memcpy()will be demonstrated in
Listing 20.6.

Moving Memory with the memmove()Function ............................................

memmove()is very much like memcpy(), copying a specified number of bytes from one
memory block to another. It’s more flexible, however, because it can handle overlapping
memory blocks properly. Because memmove()can do everything memcpy()can do (with
the added flexibility of dealing with overlapping blocks), you rarely, if ever, have a rea-
son to use memcpy(). The prototype is
void *memmove(void *dest, void *src, size_t count);
destandsrcpoint to the destination and source memory blocks, and countspecifies the
number of bytes to be copied. The return value is dest. If the blocks overlap, this func-
tion ensures that the source data in the overlapped region is copied before being over-
written. Listing 20.6 demonstrates memset(),memcpy(), andmemmove().

LISTING20.6 mem.c. A demonstration of memset(),memcpy(), and
memmove()
1: /* Demonstrating memset(), memcpy(), and memmove(). */
2:
3: #include <stdio.h>
4: #include <string.h>
4:
5: char message1[60] = “Four score and seven years ago ...”;
6: char message2[60] = “abcdefghijklmnopqrstuvwxyz”;
7: char temp[60];
8:

580 Day 20

INPUT

32 448201x-CH20 8/13/02 11:16 AM Page 580

Free download pdf