Cpp - String String Copying


strcpy_s() function copies the entire contents of one string into a designated buffer.


#include <iostream> 
#include <string.h> 

int main() /*  w  w  w . j a  va  2s  .c o m*/
    char string1[] = "this is a test!"; 
    char string2[80]; 

    strcpy_s(string2, string1); 

    std::cout << "String1: " << string1 << std::endl; 
    std::cout << "String2: " << string2 << std::endl; 
    return 0; 


A character array is created and initialized with the value of a string literal.

The strcpy() function takes two character arrays: a destination that will receive the copy and a source that will copy it.

If the source array is larger than the destination, strcpy() writes data past the end of the buffer.

strncpy() function takes a third argument that specifies the maximum number of characters to copy:

strncopy(string1, string2, 80);