WAP 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
- Read a string into a character array (
char str[20]). - Create a character pointer pointing to the start of the array:
char* p = str;. - Loop while the dereferenced pointer is not the null terminator:
while(*p != '\0'). - Increment the length, and increment the pointer (
p++) to move to the next memory address.
main.cpp
#include<iostream>
using namespace std;
int main( ) {
char str[20];
int length = 0;
cout<<"Enter any String : ";
cin.getline(str,20);
char* p = str;
while (*p != '\0') {
length++;
p++;
}
cout<<"Length of "<< str<<" = ";
cout<< length<< endl;
return 0;
}
Expected Output
Enter any String : prowess Length of prowess is : 7
Explanation of the Program
- In C++, the name of an array is actually just a pointer to its first element!
- By doing
p++, we are utilizing "Pointer Arithmetic". We are literally shifting our pointer one byte forward in RAM to point to the next character in the array until we hit the invisible\0character that marks the end of a string.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)