How To: Use ‘strcpy’ In C

On April 19, 2011, in How To, Programming, by erik

A function that I use quite often in C is strcpy. The strcpy function allows the programmer to copy one string to another. This is beneficial if you want to parse or modify a string without affecting the original or if you want to store a string in a structure during processing. The function strcpy will automatically copy the null terminating byte within your string to the destination string, how handy is that! The goal of this article is to give you a few examples of using strcpy and a few things to avoid.

Function Definition Of strcpy

The strcpy function is quite basic and is defined as:

1
2
3
4
5
// Header Include
#include <string.h>
 
// Function definition
char *strcpy(char *dest, const char *src);

As you can see from the function definition the mapping is much like assigning a value to a variable, from right to left. In this case we must ensure our char *dest has enough space allocated to copy the source string to, otherwise strcpy will write into who knows what. It is also very important that our strings do not overlap in memory otherwise the validity of the strcpy execution cannot be trusted. I always err on the side of caution and allocate the space for my soon to be copied string with malloc. For an in-depth look at malloc refer to my malloc article. When allocating memory, remember to include space for the null terminating character as well.

Example Program Using strcpy

This quick example shows the use of strcpy and includes the strlen function and the use of malloc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main ()
{
	char base_str[]="Erik was here.";
 
	// Add the + 1 for the null terminator '\0'
	char *cpy_str = (char *)malloc(strlen(base_str) + 1 * sizeof(char));
	if(cpy_str == NULL){
		fprintf(stderr, "Could not allocate memory for our strcpy.\n");
		return -1;
	}	
 
	strcpy(cpy_str,base_str);
 
	fprintf(stdout,"Base str   : -%s-\n", base_str);
	fprintf(stdout,"Copied str : -%s-\n", cpy_str);
 
	free(cpy_str);
 
	return 0;
}

The output of this program is as expected:

1
2
3
$ ./copy 
Base str   : -Erik was here.-
Copied str : -Erik was here.-

In the example above I allocated the memory dynamically, if you know that the length of the string will be static than you can create your destination string statically as well. As a quick example:

1
2
3
4
5
6
7
8
char base_str="Erik was here.";
char dest_str[20];
 
// We could also use strlen for this static allocation
char dest_str_two[strlen(base_str) + 1];
 
strcpy(dest_str,base_str);
strcpy(dest_str_two,base_str);


The strcpy Gotchas

In conclusion, strcpy is very useful for copying strings for parsing or quick duplication of string data. There are a few things to remember:

  1. If the source and destination strings overlap the use of strcpy is undefined, and could be dangerous for your data.
  2. strcpy will copy the null terminating string, if you plan to allocate memory on the fly for the destination string remember to include space for the null terminator.
  3. Ensure the destination string is long enough to store the original string including the null terminator.

There you have it, strcpy explained!

7 Responses to How To: Use ‘strcpy’ In C

  1. paul wendl baduya says:

    can you help me in making a program using strnopy?

    • erik says:

      Do you mean “strncpy()” ? I probably can, what are you trying to do?

      • lee says:

        thank you for that explanation. you mentioned in the introduction that you can copy the string to a data structure for processing. i’ve been trying to figure out how to do that for the last 12 hours. how does that work or do you have an example? this is the closest ive gotten to maybe getting some help with this. thanks in advance!

  2. [...] provides mechanism to copy a set of bytes from location to another. It is quite similar to the strcpy function I wrote about earlier. The advantage of memcpy is that you can copy strings, or bytes, or data, or structures, or [...]

  3. Dylan Kreutzfeldt says:

    I have 2 strings (first and last name) and I need to switch the names around (from Dylan Kreutzfeldt to Kreutzfeldt Dylan). But when I use strcpy it says I have too few arguments. Here is my copying sequence. I use fgets to have the user insert their name above.
    char firstName[20];
    char lastName[20];
    char temp[20];
    strcpy(char temp, char firstName);
    strcpy(char firstName, char lastName);
    strcpy(char lastName, char temp);

    Any tips would be awesome.

    • erik says:

      Hi Dylan,

      Your strcpy commands have you including the type “char”. What you want to do is simply.

      strcpy(temp, firstName);
      strcpy(firstName, lastName);

Leave a Reply

Your email address will not be published. Required fields are marked *


four + = 5

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>