C++ Program to Compare Two Strings Using Pointers

C++ Program to Compare Two Strings Using Pointers

In below program we are comparing two string with the help of pointers, without using strcmp() function. A user defined function str_cmp() is created which takes two character pointers as argument. If this function returns 1 than the strings are equal and unequal if returns 0. Just take a look on the program, if you are facing any problem to understand then feel free to ask by commenting below.

Also Read: C++ Program to reverse a string
Also Read: C++ Program to Count no. of words in a string


using namespace std;

    char str1[50],str2[50];
    int str_cmp(char*,char*);
    cout<<“Enter first string:”;
    cout<<“Enter second string:”;

        cout<<“nStrings are equal”;
        cout<<“nStrings are not equal”;

    return 0;

int str_cmp(char *s1,char *s2)


        return 1;

    return 0;

7 thoughts on “C++ Program to Compare Two Strings Using Pointers

  1. Karthik Reddy

    I see that during the str_cmp call two character strings are sent in to the function.. But in the str_cmp definition the recieving end has two charecter pointers ,can you please explain how this works

    1. Neeraj Mishra

      Actually string is itself a pointer. When str1 and str2 is passed in main() the memory address of first character of each string is passed which is stored in character pointer s1 and s2. As continuous memory allocation occurs in string so all other characters of str1 and str2 is accessed by increasing the memory address stored in pointer s1 and s2. I hope this will help you to understand the logic.

    1. Sabda Utama Rosiadi

      String itself is like an array of character. And an array can be accessed by using pointer just like Neeraj said above.

      For comparing, think it like comparing each character in both string from beginning. If comparing didn't meet the end ( character) on both string, those string must be not the same either the length or one of the character.

  2. kalyan garimella

    In this line of code if(*s1==''||*s2=='') you are comparing the length of the strings right?
    and in this line of code if(*s1==''&&*s2=='') you are comparing the equality of two strings?


Leave a Reply

Your email address will not be published. Required fields are marked *