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++
// C++ Program to illustrate how to declare pointer to // strings #include <iostream> using namespace std; int main() { // for C-style string const char * arr1[] = { "String1" , "String2" , "String3" , "String4" }; // or // for C++ style stings string arr2[4] = { "Str1" , "Str2" , "Str3" , "Str4" }; // Declare a pointer to an array of strings arr2 string* ptr_to_arr = arr2; // Accessing and printing elements of the array using // the pointer cout << "Array Elements: " << endl; for ( int i = 0; i < 4; ++i) { cout << *(ptr_to_arr + i) << " " ; } return 0; } |
Array Elements: Str1 Str2 Str3 Str4
Time Complexity: O(1)
Auxiliary Space: O(1)
How to Declare Pointer to an Array of Strings in C++?
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++.