Forum

Learn strcpy functi…
 
Notifications
Clear all

Learn strcpy function

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

The strcpy() function in C is used to copy one string into another. It’s part of the C Standard Library and defined in the <string.h> header.


🧠 What strcpy() Does

  • It copies the contents of a source string (including the null terminator \0) into a destination buffer.
  • The syntax is:
    char *strcpy(char *dest, const char *src);
    
  • It returns a pointer to the destination string.

📦 Example

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

int main() {
    char src[] = "Hello, World!";
    char dest[50];  // Make sure it's large enough

    strcpy(dest, src);

    printf("Copied string: %s\n", dest);
    return 0;
}

Output:

Copied string: Hello, World!

⚠️ Important Notes

  • No bounds checking: strcpy() does not verify if dest is large enough to hold src. This can lead to buffer overflows, which are serious security risks.
  • Safer alternative: Use strncpy() or modern functions like strcpy_s() (in Microsoft compilers) or strlcpy() (in BSD systems).

🛠 Custom Implementation (for learning)

void customStrcpy(char *dest, const char *src) {
    while (*src) {
        *dest++ = *src++;
    }
    *dest = '\0';  // Add null terminator
}

 


   
Quote
Share: