C strcpy() Function

strcpy() copies the source string (with its null character) into the destination array.

Syntax

char *strcpy(char *dest, const char *src);

Example

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

int main(void) {
    char src[] = "Hello";
    char dest[20];

    strcpy(dest, src);
    printf("dest = %s\n", dest);
    return 0;
}

Output:

Output of the above program is

dest = Hello

Why we need it

In C you cannot write dest = src; to copy a string. It does not copy the characters. You must use strcpy() or copy in a loop.

Safer way: strncpy

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

int main(void) {
    char small[6];

    strncpy(small, "Programming", sizeof(small) - 1);
    small[sizeof(small) - 1] = '\0';    // add the null ourselves
    printf("%s\n", small);
    return 0;
}

Output:

Output of the above program is

Progr

Note: The destination must be big enough for the source and its null character. If not, strcpy() writes outside the array, and the program can crash or be attacked.

Next: C strcat() Function.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.