Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find the length of String using Pointer

C Code Example — Function Programs

ADVERTISEMENT

C Program to find the length of String using Pointer

Objective

Write a C program to find the length of a string using a Pointer.

Algorithm / Approach

  1. Declare a char array str[20] and use gets() to read a string.
  2. Create a char pointer *p and point it to the start of the string: char* p = str;.
  3. Start a while loop that continues as long as the data at the pointer is not the null terminator: while (*p != '\0').
  4. Increment the length counter, and move the pointer to the next character in memory: p++.
main.c
#include<stdio.h> 
int main( ) {
 char str[20];
 int length = 0;
 printf("\nEnter any String : ");
 gets(str);
 char* p = str;
 while (*p != '\0') {
  length++;
  p++;
  }
  printf("Length of  %s is : %d", str, length);
  return 0;
}

Expected Output

Enter any String : prowess
Length of prowess is : 7

Explanation of the Program

  • In C, the name of an array (like str) acts as a pointer to its first element.
  • When you do p++ on a pointer, you aren't just doing basic math. You are performing "Pointer Arithmetic". The compiler knows p points to a char (which is 1 byte), so p++ shifts the memory address forward by exactly 1 byte, landing perfectly on the next letter.

Complexity

Time Complexity O(n) - Where n is string length.
Space Complexity O(1)
ADVERTISEMENT