Pointer Assignment 5 — Length of a String Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Length of a String Using Pointers — Walking Until '\0'

📑 On this page:
  • How a C String Lives in Memory
  • The Null Terminator and Pointer Walk
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why a C string is just a pointer to a byte array that ends with '\0'
  • How to walk a pointer through memory one character at a time
  • Two idioms for computing length: counting steps vs subtracting addresses
  • Why *p != '\0' is the essential loop condition — and what happens if you forget it
  • The difference between the string's length and its storage size

How a C String Lives in Memory

In C there is no "string type." A string is a sequence of char values stored contiguously in memory, and the end of the string is marked by a special byte: the null character, written '\0' (value 0). That's the entire contract. A char * — pointer to char — is enough to represent any string: it points at the first character, and any code consuming the string walks forward until it sees '\0'.

When you write char *s = "Hello";, the compiler stores six bytes somewhere in read-only memory: 'H', 'e', 'l', 'l', 'o', '\0'. The variable s holds the address of the first byte. If you followed s through memory, you'd find those six bytes one after another. Five letters, then a zero.

To compute the length, walk a pointer through the bytes until you hit the zero, and count how many steps you took. That's it. This is exactly what strlen does internally — nothing fancier. The function strlen exists mainly for convenience and to let the compiler optimize the walk; the algorithm is trivial once you understand the storage model.

💡 In one line: A string is a pointer to a byte sequence terminated by '\0'. Length is how far you have to walk to reach that zero.

Diagram of a string Hello stored as six bytes with a pointer walking from H to the null terminator, illustrating string length in C using pointers

The Null Terminator and Pointer Walk

Expression Meaning Example (with char *s = "Hello";)
sAddress of first charPoints at 'H'
*sCurrent character'H'
s[1]Second character'e'
*(s + i)i-th character*(s + 4) is 'o'
s++Advance to next characterMoves from 'H' to 'e'
*s != '\0'Loop condition — is not end?True until hitting '\0'
p - sDistance walkedIf p reached end, that's the length

Two consequences of this model are worth flagging now. First, the length of the string is not the size of the array or buffer. char buf[100] = "Hi"; has length 2, but its storage size is 100 bytes. strlen(buf) reports 2, because that's how far you walk before hitting '\0' — the rest of the buffer is unused (or holds garbage that may or may not contain a zero). Second, walking past the '\0' means walking into whatever comes after in memory. If you forget the terminator check, your pointer will happily keep stepping into unrelated bytes until either a random zero appears (giving a wrong, too-long length) or you segfault. The '\0' check isn't optional; it's the whole safety mechanism.

Complete C Program

Program: compute string length by walking a pointer to '\0'

#include <stdio.h>

/* Idiom 1: count characters while walking */
int string_length_count(const char *s) {
    if (s == NULL) return 0;

    int len = 0;
    while (*s != '\0') {
        len++;
        s++;
    }
    return len;
}

/* Idiom 2: advance pointer, then subtract from start */
int string_length_diff(const char *s) {
    if (s == NULL) return 0;

    const char *start = s;
    while (*s != '\0') {
        s++;
    }
    return (int)(s - start);   /* pointer subtraction gives distance */
}

int main(void) {
    const char *greeting = "Hello";
    char mutable_str[] = "Pointers";
    const char *empty = "";
    char buffer[50] = "Embedded in a buffer";

    printf("greeting      = \"%s\"  length = %d\n",
           greeting, string_length_count(greeting));
    printf("mutable_str   = \"%s\"  length = %d\n",
           mutable_str, string_length_count(mutable_str));
    printf("empty         = \"%s\"  length = %d\n",
           empty, string_length_count(empty));
    printf("buffer        = \"%s\"  length = %d\n",
           buffer, string_length_count(buffer));

    printf("\nUsing pointer-difference version:\n");
    printf("greeting length = %d\n", string_length_diff(greeting));
    printf("buffer   length = %d\n", string_length_diff(buffer));

    return 0;
}
                                    

Program Output

greeting      = "Hello"  length = 5
mutable_str   = "Pointers"  length = 8
empty         = ""  length = 0
buffer        = "Embedded in a buffer"  length = 20

Using pointer-difference version:
greeting length = 5
buffer   length = 20
                                

Note that buffer is declared as a 50-byte array, but only 20 bytes are used by the string content plus its terminator. The length function reports 20 — the actual string length — not 50, because it stops walking at the '\0' after "buffer." The empty string reports 0 because the very first byte is already '\0'.

Step-by-Step Explanation

Let's walk through the counting version first, then the pointer-difference version.

1. const char *s = "Hello";

The compiler places the six bytes H e l l o \0 somewhere in read-only memory. s receives the address of the first byte. In string_length_count, the parameter s is a copy of that address — but it points to the same bytes. The const documents that the function will not write through this pointer.

2. if (s == NULL) return 0;

If the caller passed a null pointer, we return 0 immediately rather than dereferencing. This is a defensive guard; a properly written program shouldn't pass NULL, but being defensive at the API boundary is good practice.

3. int len = 0;

The accumulator. Each character we walk past increments this by one. Alternatively, we could have used the pointer itself: at the end, p - start would give the same count. We'll see that in the second version.

4. while (*s != '\0') { len++; s++; }

This is the heart of the algorithm. On each iteration, we check the character currently pointed at — not the address, not the pointer itself, but the byte at that address. If it's not '\0', we count it and advance the pointer. When we eventually point at '\0', the condition is false, the loop exits, and len holds the count. That count is exactly the number of non-zero bytes, i.e., the string length.

5. Tracing "Hello"

Start: s points at 'H', len = 0. Iteration 1: 'H' != '\0', so len = 1, s advances to 'e'. Iteration 2: 'e' != '\0', len = 2, s advances to 'l'. Iteration 3: len = 3, s → second 'l'. Iteration 4: len = 4, s → 'o'. Iteration 5: len = 5, s → '\0'. Iteration 6: *s is '\0', condition false. Loop exits with len = 5. Correct.

6. The pointer-difference idiom

string_length_diff uses a different formulation. It saves the starting pointer in start, then advances s without counting. When the loop exits, s - start gives the number of characters between the two addresses. Why? Because pointer subtraction on pointers of the same array type yields the number of elements between them, not the number of bytes. Since each char is one byte, it happens to equal the byte count here — but the rule holds for any type. On an int *, p2 - p1 would give the number of ints, not bytes.

7. Why is string_length_diff more elegant?

Because it exploits the pointer representation directly. There is a single fact — "walk until '\0'" — and the length emerges as the difference between where you stopped and where you started. No separate counter variable is needed. Both versions compute the same result; the difference is stylistic. Most C programmers prefer the counting version in casual code because it's more explicit, but the pointer-difference version is common in optimized or compressed code.

8. The empty string

const char *empty = ""; creates a one-byte array containing just '\0'. The very first check sees '\0', the loop body never runs, and both versions return 0. This is the correct, expected behavior for an empty string. Beginners sometimes worry that "empty" might be an error — it's not; empty strings are perfectly valid and frequently occur.

9. Why const char * for the parameter?

const char *s means "pointer to const char" — the function promises not to modify the characters. This lets the caller pass string literals (which are typically read-only) without warnings, and makes the function's read-only intent explicit. If you accidentally write *s = 'x' inside, the compiler will refuse. For functions that genuinely need to modify the string (like reverse or to-upper), the parameter should be plain char * and the caller's buffer must be mutable.

10. Buffer vs string length

The buffer[50] array occupies 50 bytes, but only about 21 are meaningful — 20 characters plus the terminator. The remainder holds whatever was left there before (in this case, zeros from initialization). The length function reports 20 because that's what's between the start and the '\0'. If you wanted the size of the buffer rather than the string, you'd use sizeof buffer in main (where the array is declared), but never inside a function that received buffer as a char * — by then, only the pointer remains.

🎯 Remember this: A C string is a char * plus the promise that somewhere ahead lies a '\0'. Length is how many steps to reach it. The terminator is not part of the length — "Hello" has length 5, not 6, even though it occupies 6 bytes.

Frequently Asked Questions

1. Why not just use strlen?

You absolutely should in production code — strlen is optimized, tested, and clearer to read. This exercise is about understanding how strlen works, which helps when you later write related functions (copy, compare, reverse, etc.) or when you debug a string-handling bug. Once you can write a length function yourself, the string library stops being magic and becomes a set of patterns you recognize.

2. What happens if the string is not null-terminated?

Undefined behaviour. The walker keeps reading bytes past the intended string until it happens upon a zero byte, giving an incorrect length — sometimes drastically so. Or it crashes when it walks into a page it can't access. This is one of the most common sources of subtle bugs in C, and it's why every string-manipulating function must respect the terminator convention strictly.

3. Does the length include the null terminator?

No. The length is the number of characters before the null terminator. "Hello" has length 5, and it's stored in 6 bytes: 'H','e','l','l','o','\0'. If you need the total bytes needed to store the string (including terminator), that's length + 1. This distinction matters when allocating buffers: malloc(len + 1), not malloc(len).

4. Can I compute length using sizeof?

Only in certain contexts. sizeof("Hello") gives 6 — the size of the array literal including the terminator. sizeof(str) gives the size of the char * variable (typically 8 bytes), not the string. To use sizeof correctly for length, you'd need sizeof(s) - 1 where s is an array declared in scope like char s[] = "Hello";. Once s decays to a pointer (for example, when passed to a function), sizeof no longer tells you anything about the string's content.

5. What if the string contains a null character in the middle?

Then that's where the length stops. char s[] = {'A', 'B', '\0', 'C', 'D', '\0'}; is a valid C string of length 2 — "AB". The bytes after '\0' are physically present but not part of the string from C's perspective. If you needed to store arbitrary bytes including zeros, you'd use a length-prefixed structure or a different convention — a byte array of known size, not a C-style string. That's exactly what memcpy and friends are for.

6. Is this O(n) in time and O(1) in space?

Yes. The function walks through each character exactly once — that's O(n) time, where n is the string length. Memory usage is constant (a pointer and an int), regardless of string length — that's O(1) space. Both are optimal for this problem: you can't compute length without visiting every character (unless the length is stored elsewhere, which would be a different data structure).

💡 Tip: Once this works, try the same walk but without the '\0' check — advance for a fixed count of, say, 100 characters and see what happens. On most systems, you'll either read garbage or crash. That experiment makes the terminator convention visceral: it's not just a stylistic choice, it's the safety net that makes C strings possible.

📖 Related Tutorials

  • 4. Reverse an Array Using Pointers
  • 6. Concatenate Two Strings Using Pointers
  • 7. Compare Two Strings Using Pointers
  • 8. Copy One String to Another Using Pointers
  • 19. Reverse a String Using Pointers
  • 23. Length of a String — Function Version
  • All 30 Pointer Assignments

Previous Topic: -->> 4. Reverse an Array Using Pointers   ||   Next Topic: -->> 6. Concatenate Two Strings 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.