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
- Declare a char array
str[20]and usegets()to read a string. - Create a char pointer
*pand point it to the start of the string:char* p = str;. - Start a
whileloop that continues as long as the data at the pointer is not the null terminator:while (*p != '\0'). - 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 knowsppoints to achar(which is 1 byte), sop++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)