cs24-24fa strcpy

Introduction to Computing Systems (Fall 2024)

Name

strcpy, strncpy - copy a string

Synopsis

1
2
3
4
#include <string.h>

char *strcpy(char *dest, const char *src);
char *strncopy(char *dest, const char * src, size_t n);

Description

The strcpy() function copies the string pointed to by src including the terminating null byte (‘\0’), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

The strncopy() function is similar, except that at most n bytes of src are copied. Note that if there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated. If the length of src is less than n, strncopy() writes additional null bytes to dest to ensure that a total of n bytes are written.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <assert.h>
#include <string.h>

int main() {
    char src[23] = "hello, i'm an example!";
    char dest1[23];
    char dest2[23];

    // Copy entire string to first destination.
    strcpy(dest1, src);
    assert(strcmp(src, dest1) == 0);

    // Fill dest2 with null bytes, then copy five characters.
    memset(dest2, '\0', sizeof(dest2));
    strncpy(dest2, src, 5);
    assert(strcmp("hello", dest2) == 0);
}

Return Value

Upon completion, the strcpy() and strncpy() functions return a pointer to the destination string dest.

See Also

memmove(), memset(), memcpy(), strcmp()