C Program to Copy String Using Pointers

C Programming Examples
C String Programs
C Loop Programs
C Function Programs
C Array Programs
C Integer Number Programs
C File I/O Programs

C program to Copy string without using strcmp() function by creating our own function which uses pointers.


void copy_string(char*, char*);

    char source[100], target[100];    
    printf("Enter source string\n");    
    copy_string(target, source);    
    printf("Target string is \"%s\"\n", target);    
    return 0;

void copy_string(char *target, char *source)
        *target = *source;        
    *target = '\0';
Output of program:
Enter source string
Target string is "w3schools.in"

This program is written to demonstrate how to copy a string using pointers. Here it will teach you how to create your own function which uses the concept of pointers. So first of all, you have to include the stdio header file using the include preceding by # which tells that the header file needs to be process before compilation, hence named preprocessor directive.

Then you have to define the main() function and it has been declared nothing so by default it is integer heche returns integer. The inside the main() function, you have to take two character arrays name source[100] and target[100].

Then the printf() is used to display the message Enter source string\n. Then the gets() function is used to take the string from the user and store it in the character array name source. Then you have to call the user defined function copy_string(target, source); from within the main() which is declared and defined after the main() scope. The printf() function again used to display the target string copied from the source string.

Now, after the main() ends, the user-defined function is declared and defined where its return type is void, then the name of the function - copy_string() which passes two character type pointer values to the calling function. Then the while loop is used which continues if the *source is not zero and inside while block, it stores the source values to target values using a pointer and incrementing both the values of source and the target by 1. At the end of the loop, the *target is initialized with null character i.e. \0.

Here are few other related articles for you to read:

Scroll Back to Top