C Program to Find Length of a String Using Pointers

1. Introduction

Strings in C are represented as arrays of characters terminated by a null character (\0). Pointers offer a way to traverse these arrays and manipulate the data without using array indexing. One common operation on strings is determining their length. While there are library functions like strlen to get the string length, using pointers provides a clear view of how such operations are carried out at a basic level.

2. Program Overview

1. Declare a character array (string) and a pointer to traverse the string.

2. Use the pointer to iterate through the string until the null character is encountered.

3. Count the number of iterations to find the string's length.

3. Code Program

#include <stdio.h>

// Function to find the length of a string using pointers
int stringLength(char *str) {
    int length = 0;
    while (*str) {       // Loop until the end of the string
        str++;          // Move to the next character
    return length;

int main() {
    char input[100];

    // Ask the user for the string input
    printf("Enter a string:\n");
    gets(input);       // Read the string

    // Calculate and display the string length
    printf("Length of the string: %d\n", stringLength(input));

    return 0;


Enter a string:
Hello, world!
Length of the string: 13

4. Step By Step Explanation

1. A character array named input is declared to hold the input string from the user.

2. The function stringLength calculates the length of a given string:

- A counter variable length is initialized to zero.

- The pointer str is used to traverse the string. The loop iterates as long as the current character pointed by str is not the null character (\0).

- For each iteration, the length counter is incremented, and the pointer str