c
  1. c-program-to-copy-string-without-using-strcpy

Program to Copy String Without Using strcpy() - (C Programs)

The strcpy() function is commonly used in C programming to copy a string from one memory location to another. However, it is not always the best option for copying strings, especially if the destination string is not allocated with enough memory. In this tutorial, we'll discuss how to write a C program to copy a string without using the strcpy() function.

Syntax

There is no specific syntax for copying a string without using the strcpy() function.

Example

Here is an example program that copies a string without using the strcpy() function:

#include <stdio.h>

int main()
{
    char source_string[] = "Hello, world!";
    char destination_string[20];

    int i = 0;
    while (source_string[i] != '\0')
    {
        destination_string[i] = source_string[i];
        i++;
    }
    destination_string[i] = '\0';

    printf("Source string: %s\nDestination string: %s\n", source_string, destination_string);

    return 0;
}

Output

When you run the program, it should display the following output:

Source string: Hello, world!
Destination string: Hello, world!

Explanation

In the above program, we first declare a source string and a destination string. We then use a while() loop to copy each character of the source string to the corresponding position in the destination string. Finally, we add a null character to the end of the destination string to terminate it properly.

Use

Copying strings without using the strcpy() function can be useful in situations where the destination string is not allocated with enough memory to hold the entire source string. By copying the string character by character, we can ensure that the destination string is allocated with enough memory.

Summary

In this tutorial, we discussed how to write a C program to copy a string without using the strcpy() function. We covered the syntax, example, explanation, use, and concluded that by copying a string character by character, we can ensure that the destination string is allocated with enough memory for the entire source string.

Published on: