How to Declare Pointer to an Array of Strings in C++?
Last Updated :
05 Mar, 2024
In C++, an array of a string is used to store multiple strings in contiguous memory locations and is commonly used when working with collections of text data. In this article, we will learn how to declare a pointer to an array of strings in C++.
Pointer to Array of String in C++
If we are working with C-style strings, we can directly declare the pointer to array of strings as double pointer to and for std::string
object we need to declare a pointer of std::string type.
Syntax to Declare Pointer to an Array of String in C++
char **ptr
For std::string object use the below syntax:
string* pointerToArray;
C++ Program to Declare a Pointer to an Array of Strings
The following program illustrates how to declare a pointer to an array of strings in C++
C++
#include <iostream>
using namespace std;
int main()
{
const char * arr1[]
= { "String1" , "String2" , "String3" , "String4" };
string arr2[4] = { "Str1" , "Str2" , "Str3" , "Str4" };
string* ptr_to_arr = arr2;
cout << "Array Elements: " << endl;
for ( int i = 0; i < 4; ++i) {
cout << *(ptr_to_arr + i) << " " ;
}
return 0;
}
|
Output
Array Elements:
Str1 Str2 Str3 Str4
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...