C Online Compiler
Example: String Copying in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// String Copying #include <stdio.h> #include <string.h> // Required for strcpy() int main() { // Step 1: Declare source and destination strings char source[] = "Copy this text."; char destination[50]; // Ensure destination has enough space // Step 2: Use strcpy() to copy source to destination strcpy(destination, source); // Step 3: Print both strings to verify the copy printf("Source String: \"%s\"\n", source); printf("Destination String: \"%s\"\n", destination); // Example with strncpy for safety (copies at most n characters) char safe_source[] = "Too long for small buffer"; char small_destination[10]; // Buffer size 10, meaning 9 chars + '\0' // Copy at most 9 characters from safe_source to small_destination strncpy(small_destination, safe_source, sizeof(small_destination) - 1); small_destination[sizeof(small_destination) - 1] = '\0'; // Manually null-terminate printf("\nSafe Copy Example:\n"); printf("Source: \"%s\"\n", safe_source); printf("Destination (max 9 chars): \"%s\"\n", small_destination); return 0; }
Output
Clear
ADVERTISEMENTS