C Program To Implement String Compare Function using Pointer

In string.h header file, strcmp function is readily available which we can use for string comparison, here this tutorials provides the logic of same function using pointers. this is basically for better understand the concepts of pointers and user defined functions.

C Program To Implement String Compare Function using Pointer


String-Compare-Function-using-pointer (31 downloads)

In above code, the function name stringcmp takes two parameters as pointer variable of character type. its points to char array passed from main function or calling function.  strcmp function returns a zero if both strings are identical or equal , returns  positive integer if string first is greater than second , returns negative number if second string is greater than first. this user defined function stringcmp returns integer values by similar way.

Here pointer p and q points to nm1 and nm2 respectively. To compare  each character from both strings nm1 and nm2. iterate pointer p up to null character. if character from p and q (which is character from nm1 and nm2 ) are not equal then return the difference of ascii code of characters ( *p – *q ). 

In this example first two characters are equal, third character is T from nm1 & C from nm2 string. so return the difference between T and C which is 17 ( as ascii code of T is 84 and ascii code of C is 67). Here return value is positive hence first string is greater.