The length of a string using pointers
Write a program to find the length of a string using pointers. Examples:
Input : given_string = “geeksforgeeks”
Output : length of the string = 13Input : given_string = “coding”
Output : length of the string = 6
Prerequisite : Pointer in C
Approach Used : In this program we make use of * operator. The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer. In the below program, in string_length function we check if we reach the end of the string by checking for a null represented by ‘\0’ .
CPP
// C++ program to find length of string// using pointer arithmetic.#include <iostream>using namespace std;// function to find the length// of the string through pointersint string_length(char* given_string){ // variable to store the // length of the string int length = 0; while (*given_string != '\0') { length++; given_string++; } return length;}// Driver functionint main(){ // array to store the string char given_string[] = "geeksforgeeks"; cout << string_length(given_string); return 0;} |
Output:
13
Time Complexity: O(N)
Auxiliary Space: O(1)





Please Login to comment...