strcpy() in C: Copy a String

strcpy() copies a null-terminated source string, including its terminating \0, into a destination array. The destination must have enough space for the complete source string.

Syntax Top ↑

strcpy(destination, source);

Basic strcpy() Example Top ↑

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

int main(void) {
    char source[] = "My First Name";
    char destination[30];

    strcpy(destination, source);
    printf("%s\n", destination);
    return 0;
}

Copy a String Manually Top ↑

#include <stdio.h>

int main(void) {
    char source[] = "welcome to c program";
    char destination[100];
    size_t i = 0;

    while (source[i] != '\0') {
        destination[i] = source[i];
        i++;
    }
    destination[i] = '\0';

    printf("%s\n", destination);
    return 0;
}

Copy User Input Top ↑

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

int main(void) {
    char source[100];
    char destination[100];

    printf("Enter a string: ");
    if (fgets(source, sizeof(source), stdin) == NULL) {
        return 1;
    }

    strcpy(destination, source);
    printf("Copied string: %s", destination);
    return 0;
}

Important Capacity Rule Top ↑

strcpy() does not know the size of the destination array. Copying a source string that is too large causes undefined behavior. Use an adequately sized destination and validate input lengths when the source size is not controlled.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer