Pointer Assignment 7 — Compare Two Strings Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Compare Two Strings Using Pointers — Walking in Parallel, Character by Character

📑 On this page:
  • How Comparison Works in Memory
  • The Three Outcomes of Strcmp
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to walk two pointers in parallel through two strings
  • Why comparison stops at the first differing character
  • What "lexicographic order" means and why it matters
  • How strcmp returns a negative, zero, or positive value
  • The classic pitfall of comparing pointers instead of characters

How Comparison Works in Memory

Comparing two strings means walking through both of them character by character, in lockstep, and finding the first position where they differ. If you reach the end of both strings without finding a difference, they are equal. If you find a difference at some position, the string whose character has a smaller ASCII value comes "first" — that's what we call lexicographic (dictionary) order.

This is exactly what strcmp does. It takes two pointers — one to each string — and advances both while the characters they point at are equal and not yet at the terminator. When the loop exits, either both pointers are at the terminator (strings equal), or one character differs (the one with the smaller ASCII code sorts first). The return value encodes that outcome: negative, zero, or positive.

The pointer-only approach makes the parallel walk explicit. You'll use two pointers, a single while loop that advances both, and a final comparison of the two characters the pointers stopped at. No array indexing, no strlen — just pointer arithmetic.

💡 In one line: Comparison = walk two pointers side-by-side until they disagree or both hit '\0'. The sign of the first differing character's difference tells you which string comes first.

Diagram showing two strings being compared in memory, with two pointers walking in parallel and stopping at the first differing character

The Three Outcomes of Strcmp

Outcome Meaning Return value
*p < *qFirst string comes before secondNegative number
*p == *q == '\0'Strings are identicalZero
*p > *qFirst string comes after secondPositive number

The comparison is character-based. 'A' (65) is less than 'B' (66), so "Apple" comes before "Banana". 'a' (97) is greater than 'A' (65), so "apple" comes after "Apple" — this is why case-insensitive comparison (like strcasecmp) is a separate function. And a prefix like "Hell" comes before "Hello" because the terminator ('\0', ASCII 0) is smaller than any printable character.

Complete C Program

Program: compare two strings using parallel pointer walks (implementation of strcmp)

#include <stdio.h>

/* Compare two strings lexicographically.
   Returns <0 if s1 < s2, 0 if s1 == s2, >0 if s1 > s2. */
int str_compare(const char *s1, const char *s2) {
    if (s1 == NULL || s2 == NULL) {
        return -1;  /* treat NULL as "less than" anything */
    }

    const char *p = s1;
    const char *q = s2;

    /* Walk both pointers while characters match and we haven't hit the end */
    while (*p != '\0' && *q != '\0' && *p == *q) {
        p++;
        q++;
    }

    /* At this point, either *p != *q, or one/both hit '\0' */
    return (unsigned char)*p - (unsigned char)*q;
}

int main(void) {
    const char *a = "Apple";
    const char *b = "Banana";
    const char *c = "Apple";
    const char *d = "App";

    int r1 = str_compare(a, b);
    int r2 = str_compare(a, c);
    int r3 = str_compare(a, d);

    printf("Compare \"%s\" vs \"%s\"\n", a, b);
    if (r1 < 0)      printf("  Result: \"%s\" comes before \"%s\" (r = %d)\n", a, b, r1);
    else if (r1 > 0) printf("  Result: \"%s\" comes after \"%s\"  (r = %d)\n", a, b, r1);
    else             printf("  Result: strings are equal (r = %d)\n", r1);

    printf("\nCompare \"%s\" vs \"%s\"\n", a, c);
    if (r2 < 0)      printf("  Result: \"%s\" comes before \"%s\" (r = %d)\n", a, c, r2);
    else if (r2 > 0) printf("  Result: \"%s\" comes after \"%s\"  (r = %d)\n", a, c, r2);
    else             printf("  Result: strings are equal (r = %d)\n", r2);

    printf("\nCompare \"%s\" vs \"%s\"\n", a, d);
    if (r3 < 0)      printf("  Result: \"%s\" comes before \"%s\" (r = %d)\n", a, d, r3);
    else if (r3 > 0) printf("  Result: \"%s\" comes after \"%s\"  (r = %d)\n", a, d, r3);
    else             printf("  Result: strings are equal (r = %d)\n", r3);

    return 0;
}
                                    

Program Output

Compare "Apple" vs "Banana"
  Result: "Apple" comes before "Banana" (r = -1)

Compare "Apple" vs "Apple"
  Result: strings are equal (r = 0)

Compare "Apple" vs "App"
  Result: "Apple" comes after "App"  (r = 108)
                                

The first comparison stops at position 0: 'A' (65) vs 'B' (66). Since 'A' < 'B', "Apple" comes first, and the function returns 65 - 66 = -1. The second comparison walks all the way through both strings — every character matches — and both hit '\0' at the same time, so the function returns 0 - 0 = 0. The third comparison walks through "App" in both strings, then p points at 'l' (108) and q points at '\0' (0). The difference is 108 - 0 = 108, a positive number, so "Apple" comes after "App".

Step-by-Step Explanation

Let's trace the pointers through the three test cases.

1. Setup

The function receives two pointers, s1 and s2, each pointing at the first character of its string. We make local copies p and q so that advancing them doesn't disturb the caller's pointers. We mark both parameters const char * because we're only reading, never writing — that also lets callers pass string literals without warnings.

2. The parallel walk

The loop condition has three parts, joined by &&:

  • *p != '\0' — the first string hasn't ended.
  • *q != '\0' — the second string hasn't ended.
  • *p == *q — the current characters are equal.

All three must be true to keep walking. The moment any one becomes false, the loop exits. That's the key insight: we stop at the first difference or at the end of either string, whichever comes first. Then one comparison at the end resolves the outcome.

3. Comparing "Apple" and "Banana"

Iteration 1: *p = 'A', *q = 'B'. They're not equal, so the third condition fails immediately. The loop body never runs. After the loop, *p = 'A' (65), *q = 'B' (66). Return 65 - 66 = -1. A negative result means the first string is lexicographically less, i.e., comes first.

4. Comparing "Apple" and "Apple"

Iterations 1–5: 'A' matches 'A', 'p' matches 'p', and so on. Both pointers advance in lockstep. Iteration 6: both *p and *q are '\0'. The first condition *p != '\0' is false, so the loop exits — we've reached the end of the first string with every character matching. After the loop, both *p and *q are '\0', so return 0 - 0 = 0. Zero means equal.

5. Comparing "Apple" and "App"

Iterations 1–3: 'A', 'p', 'p' all match; both pointers advance. Iteration 4: *p = 'l', *q = '\0'. The second condition *q != '\0' is false, so the loop exits. After the loop, *p = 'l' (108), *q = '\0' (0). Return 108 - 0 = 108. A positive result means the first string comes after the second. This makes sense: "App" is a prefix of "Apple", so it sorts first.

6. Why cast to unsigned char?

Because char may be signed on some platforms. If the bytes being compared happen to be non-ASCII (for example, accented characters or bytes from a UTF-8 sequence), a signed char would interpret bytes above 127 as negative numbers. That would make the difference calculation wrong — for example, a byte with value 200 would be treated as -56. Casting to unsigned char before subtracting gives the correct 0–255 range for each byte, so the difference is meaningful and monotonic. This is exactly what standard strcmp does internally.

7. What if the difference is larger than 1?

The function returns the actual difference between the ASCII codes, not just -1 or 1. That's why "Apple" vs "App" returns 108, not 1. The sign of the return value is what callers should rely on — negative, zero, or positive — but returning the raw difference is a common convention because it's free to compute and immediately tells you the ordering. If you only ever need the sign, you could normalize to -1/0/+1, but there's no reason to.

8. Why the NULL guard?

Dereferencing a NULL pointer is undefined behaviour — usually a crash. A strcmp-style function is typically a building block, so guarding the entry point costs very little and turns a possible segfault into a clean, predictable "less than" result. A correct caller never passes NULL, but defensive programming is a good habit for reusable code.

9. Can I write this more compactly?

Yes — the loop condition can be folded into a single expression if you're comfortable with the idiom:

while (*p && *p == *q) { p++; q++; }
return (unsigned char)*p - (unsigned char)*q;
                                

This works because if *q is '\0' before *p is, the equality fails (one is zero, the other isn't) and the loop exits — then the final subtraction compares *p against 0. If both are '\0', the loop has already exited and returns 0. The longer form is easier to read and audit; both are correct.

10. The classic pitfall: comparing pointers

A common beginner mistake is writing if (s1 == s2) to check whether two strings are equal. That compares the pointer addresses, not the string contents. Two different arrays can contain the same characters at different addresses, so s1 == s2 would be false even though the strings are identical. Conversely, two pointers to the same array would be equal even if you wanted to compare overlapping substrings. Always compare the characters the pointers point at, which is what this function does.

11. How is this different from strcoll or case-insensitive comparison?

strcmp (and this function) compares raw byte values. That's fine for ASCII, but languages with accented characters, ligatures, or locale-specific ordering rules may sort differently than plain byte order suggests — that's what strcoll handles. And strcmp is case-sensitive: 'A' (65) is less than 'a' (97), so "abc" comes after "ABC". For case-insensitive comparison, the usual approach is to normalize both strings to the same case (using tolower) or to use a platform-specific function like strcasecmp. This function is the foundation — once you understand it, the variants are small modifications.

12. Is the input modified?

No. We only read *p and *q, never assign to them. The pointers p and q advance inside the function, but they are local copies of the caller's pointers, so the caller's variables are unaffected. Both strings are unchanged after the call. The const qualifiers on the parameters document this: the function will never write through those pointers, and the compiler will enforce it.

🎯 Remember this: Comparison walks two pointers in parallel and stops at the first difference. The sign of the difference at the stopping point tells you the lexicographic order. Use the sign, not the exact value — but do return the raw difference, as standard strcmp does.

Frequently Asked Questions

1. Why not just use strcmp?

In production code, strcmp is the standard choice — tested, portable, and likely optimized. This exercise teaches you how it works so that you can write bounded variants (strncmp), case-insensitive versions, or custom comparison rules for structures. It's also a very common interview question and a fundamental building block for sorting algorithms.

2. What does the return value mean exactly?

A negative value means the first string is lexicographically less than the second. Zero means they are equal. A positive value means the first string is greater. This mirrors the convention of strcmp and similar functions, making it easy to reuse: qsort comparators, binary search, and sort functions all expect this pattern. The exact magnitude is usually ignored — only the sign matters.

3. How does lexicographic order work for mixed-case strings?

It compares raw ASCII values, so uppercase letters (65–90) come before lowercase letters (97–122). This means "Zebra" comes before "apple" even though a dictionary would list "apple" first. That's why case-insensitive comparison is a separate operation. If you need dictionary-style ordering with case folded, convert both strings to lowercase before comparing — or use a locale-aware function like strcasecmp or strcoll.

4. Can this compare strings of different lengths?

Yes. The loop walks until either pointer reaches the terminator, so strings of different lengths are handled correctly. When one ends first, the other's remaining character (or terminator) determines the result. A prefix comes before the longer string: "car" < "cart" because '\0' (0) is less than 't' (116).

5. What is the difference between strcmp and strncmp?

strncmp takes a third argument — the maximum number of characters to compare. This is useful when comparing prefixes, or when one string might not be null-terminated within the expected bound. strcmp walks until a terminator or a mismatch, which is fine when both strings are guaranteed valid. If you're parsing untrusted input, bounded comparison is safer because it can't run off the end of a malformed buffer.

6. What if both pointers are NULL?

This function handles it by returning -1 (treating NULL as less than anything, including another NULL, so it would return 0 for two NULLs in a strict reading — but the guard short-circuits before the pointers are used). In general, passing NULL to a string function is a programming error, not a case to design around. The guard is a safety net, not a contract.

💡 Tip: After this works, try implementing strncmp — the same loop, but with a size_t n counter that decrements on each iteration and stops the loop when it hits zero. It's a small change that makes the function safe for comparing prefixes and bounded input, and it's a natural next step.

📖 Related Tutorials

  • 5. Length of a String Using Pointers
  • 6. Concatenate Two Strings Using Pointers
  • 8. Copy One String to Another Using Pointers
  • 18. Compare Two Strings — Function Version
  • 20. Concatenate Two Strings — Function Version
  • All 30 Pointer Assignments

Previous Topic: -->> 6. Concatenate Two Strings Using Pointers   ||   Next Topic: -->> 8. copy one string to another using pointers


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.