8/1/2018 - 12:11 AM

2 ways to copy strings in C

strcpy() and memcpy()

There are 2 ways you can copy one string to another:

1. strcpy - copy a string
#include <string.h>
string strcpy(string destination, string source);
strcpy copys string source into string destination.
A string, destination, is returned.

One important thing about copying a string is to use "malloc()" to allocate new memory block for the destination string first. Relate to "Use of * for strings in C" for more explaination.

Example code:

    // get a string
    char *s = get_string("s: ");
    if (!s)
        return 1;
    // allocate memory for another string
    char *t = malloc((strlen(s) + 1) * sizeof(char));
    if (!t)
        return 1;
    // copy string into memory
    for (int i = 0, n = strlen(s); i <= n; i++)
        t[i] = s[i];
* Copy string contents into the new memory block can also be written using "strcpy(des, src);" The result is the same. Main thing is to allocate new memory block for string "t" first.
EXAMPLES in cs50 reference page:
string source = "CS50";
char destination[50];
strcpy(destination, source);
printf("%s is the same as %s: %d\n", destination, source, strcmp(source, destination));
CS50 is the same as CS50: 0

2. memcpy() - copy memory area


#include <string.h>
void * memcpy(void * dest, const void * src, size_t n);


The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove(3) if the memory areas do overlap.

The C library function void *memcpy(void *str1, const void *str2, size_t n) copies n characters from memory area str2 to memory area str1.

The memcpy() function returns a pointer to dest.


This program uses both functions:

#include <stdio.h>
#include <string.h>

int main () {
   const char src[50] = "";
   char dest[50];
   printf("Before memcpy dest = %s\n", dest);
   memcpy(dest, src, strlen(src)+1);
   printf("After memcpy dest = %s\n", dest);


Before memcpy dest = Heloooo!!
After memcpy dest =