C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Find length of string using pointers

C Program: Find length of string using pointers

C

#include <stdio.h>

 

int main() {

    char str[100];

    char *ptr;

    int length = 0;

 

    // Input string

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    // Assign pointer to string

    ptr = str;

 

    // Traverse string until null character

    while (*ptr != '\0') {

        length++;

        ptr++;

    }

 

    // Subtract 1 to ignore newline character (if present)

    if (str[length - 1] == '\n') {

        length--;

    }

 

    // Display result

    printf("Length of the string = %d\n", length);

 

    return 0;

}

Output

 
OUTPUT :

Enter a string: ITDeveloper
Length of the string = 11

Explanation

  • The pointer ptr is assigned the address of the first character in the string.
  • The program traverses the string character by character using ptr++ until it reaches the null terminator '\0'.
  • length counts the total number of characters.
  • If the input includes a newline (from fgets()), it is subtracted from the count.