In this source code example, we will see how to use the strcpy() function in C programming with an example.
strcpy() Function Overview
The strcpy() function is a common and essential string handling function in C, which copies a string from the source to the destination.
Here are the key points:
1. Part of the <string.h> library.
2. Syntax:
char *strcpy(char *destination, const char *source);
3. Returns a pointer to the destination.
4. Stops copying upon encountering a '\0' in the source.
5. Requires the destination to be large enough to store the source.
6. Direct use can be unsafe, leading to buffer overflows.
7. strncpy() is a safer variant when used correctly, as it allows specifying a maximum number of characters to copy.
Source Code Example
#include <stdio.h>
#include <string.h>
int main() {
char original[] = "Hello, World!";
char copy[50]; // Ensure the destination has enough space
// Using strcpy() to copy the content
strcpy(copy, original);
printf("Original String: %s\n", original);
printf("Copied String: %s\n", copy);
// Another example: Copying part of the string using a pointer
char *ptr = original + 7; // Pointing to 'W' in "World!"
strcpy(copy, ptr);
printf("Partial Copied String: %s\n", copy);
return 0;
}
Output
Original String: Hello, World! Copied String: Hello, World! Partial Copied String: World!
Explanation
1. We define a string original that contains "Hello, World!".
2. Another character array copy is initialized with enough space to hold the copied string.
3. The strcpy() function is then used to copy the content of original into copy.
4. Both the original and copied strings are printed.
5. In the next example, we demonstrate copying a part of the string. A pointer ptr is set to point to the 'W' in "World!".
6. The strcpy() function is then used to copy from this pointer to the end of the string into copy.
7. The partially copied string is printed.
Comments
Post a Comment