C Program to Print the Length of a String using Pointers
Last Updated :
11 Mar, 2023
Prerequisite: Pointer in C
This article demonstrates the program to find the length of the string using pointers in C.
Examples:
Input : given_string = “geeksforgeeks”
Output : length of the string = 13
Input : given_string = “coding”
Output : length of the string = 6
Approach: In this program, we make use of the (*) dereference operator. The (*) dereference operator is used to access or modify the value of the memory location pointed by the pointer.
In the below program, in the string_length function, we check if we reach the end of the string by checking for a null represented by ‘\0’.
C
#include <stdio.h>
int string_length( char * given_string)
{
int length = 0;
while (*given_string != '\0' ) {
length++;
given_string++;
}
return length;
}
int main()
{
char given_string[] = "GeeksforGeeks" ;
printf ( "Length of the String: %d" ,
string_length(given_string));
return 0;
}
|
Output
Length of the String: 13
Time Complexity: O(N)
Auxiliary Space: O(1)
where N is the length of the string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...