Copy string to another using pointers

C program to copy one string to another using pointers


Program

#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
   char str1[MAX], str2[MAX];
    char *ptr1, *ptr2;

    printf("Enter any string\t:");
    gets(str1);

    ptr1 = str1;
    ptr2 = str2;

    while(*ptr1 != '\0')
    {
        *ptr2 = *ptr1;
        ptr1++;
        ptr2++;
    }
    *ptr2 = '\0';       //Makes sure that the string is NULL terminated

    printf("\nFirst string\t:%s",str1);
    printf("\nSecond string\t:%s",str2);

    getch();
}

Output

Enter any string        :welcome to coursecrux.com

First string    :welcome to coursecrux.com
Second string   :welcome to coursecrux.com

Explanation

In the above program, a string is taken as an input from the used and stored in some variable say 'str1'. Another variable 'str2' is taken, in which string is to be copied. Two pointers 'ptr1' and 'ptr2' are declared and points to 'str1' and 'str2' respectively.
ptr1 = str1;
ptr2 = str2;
Each character is traversed in the string 'str1' and copied to 'str2' using the statement
*ptr2 = *ptr1;
Both the pointers are then incremented by 1, so that they point to the next character which is to be copied and where to be copied.
ptr1++;
ptr2++;
The NULL character ('\0') is encountered at the end of the string 'str1', making the while loop to exit. At the end of 'str2', NULL character is entered, to end the string.
*ptr2 = '\0';

In C programming, NULL character is represented with 0.
Hence, we can embed the string copy logic *ptr2 = *ptr1; in the while loop condition.
Means, you can also write the above while loop as while(*(ptr2++) = *(ptr1++));.
This will copy characters from str1 to str2 and finally check the current str2 character for NULL.
The loop terminates, if current character copied to str2 is NULL. As NULL is copied to str2, there is no need to explicit adding it at the end.
So, the program in more geeky way is in "Method 2" tab.

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
    char str1[MAX], str2[MAX];
    char *ptr1, *ptr2;

    printf("Enter any string\t:");
    gets(str1);

    ptr1 = str1;
    ptr2 = str2;

    while(*(ptr2++) = *(ptr1++));

    printf("\nFirst string\t:%s",str1);
    printf("\nSecond string\t:%s",str2);

    getch();
}

Output

Enter any string        :welcome to coursecrux.com

First string    :welcome to coursecrux.com
Second string   :welcome to coursecrux.com