Notifications
Clear all
Topic starter 15/08/2025 9:26 pm
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 ifdest
is large enough to holdsrc
. This can lead to buffer overflows, which are serious security risks. - Safer alternative: Use
strncpy()
or modern functions likestrcpy_s()
(in Microsoft compilers) orstrlcpy()
(in BSD systems).
🛠 Custom Implementation (for learning)
void customStrcpy(char *dest, const char *src) {
while (*src) {
*dest++ = *src++;
}
*dest = '\0'; // Add null terminator
}