Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Convert String to Char Array in C++
Next article icon

Array of Pointers to Strings in C++

Last Updated : 21 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, an array is a homogeneous collection of data that is stored in a contiguous memory location. We can store almost all types of data as array elements. In this article, we will learn how to store the array of pointers to strings in C++.

Array of Pointers to Strings in C++

A pointer to a string means that the pointer points to the first character in the sequence of characters that is terminated by a null character. In C++, we can use this pointer to represent strings.

An array of pointers to strings will simply be an array whose each element is a pointer that points to a string. We can also visualize this array as a 2D array of characters where each row contains a string and its size is also equal to that string.

To create an array of pointers to strings in C++, we declare an array of pointer types where each element points to a character.

Declaration of Array of Pointers to Strings

The basic form of declaring an array of pointers to strings in C++ is shown below.

Syntax

data_type* array_name[x];

where,

  • data_type: Type of data to be stored in each element. In this case, it’s char for strings.
  • array_name: name of the array
  • x: Number of pointers (or strings).

For Example, we can declare an array of pointers to strings say ‘str’ with 5 strings as:

char* str[5];

Note: In this type of declaration, the array is allocated memory in the stack and the size of the array should be known at the compile time i.e. size of the array is fixed. We can also create an array dynamically in C++ by using new keyword as shown below.

Initialization of Array of Pointers to Strings

We can initialize an array of pointers to strings in C++ by using an initializer list as shown in the example below

char* str[5] = {"Hello", "World", "I", "am", "here"};

Accessing Elements of Array of Pointers to Strings

We can access the strings stored in this array using their index value as usual:

array_name[i]

where i is the index of the string.

Moreover, we can even access the character of a particular string by treating this array as 2d array.

array_name[i][j]

where j is the index of the character.

We can also use the pointer representation for accessing the character

*(array_name[i] + j)

or even treat the array as pointer too.

*(*(array_name + i) + j)

The above is a property of array and is same for all other types of array. To learn more, visit - C++ Arrays

Updating the Elements of Array of Pointers to Strings

The elements of array of pointers to strings are pointers themselves so we can easily change where they points to by simply assigning the new address. So, we can directly assign the new string to the index where we want to.

Syntax

array_name[index] = "newString";

Its fine till you want to update or modify the array element by element but dont try to change the characters of the string that an element is pointing to because they are stored as string literals in the read-only memory. Although it is possible to get their address, but as the name implies, it is not legal to modify the values stored in the read-only memory.

Example of Array of Pointer to Strings

C++
// C++ Program to illustrate how to use array of pointers to // strings #include <cstring> #include <iostream> using namespace std;  #define SIZE 5  int main() {     // declaring and initializing array of pointers     char* names[SIZE]         = { "Rahul", "Aman", "Abdul", "Ram", "Pradeep" };      // printing the last character of each string     for (int i = 0; i < SIZE; i++) {         int currentStrLen = strlen(names[i]);          // accessing character         char lastChar = names[i][currentStrLen - 1];          cout << lastChar << " ";     }     cout << endl;      // printing whole strings     for (int i = 0; i < SIZE; i++) {         cout << names[i] << " ";     }     cout << endl;      // updating element     names[2] = "Fashil";      // printing whole strings     for (int i = 0; i < SIZE; i++) {         cout << names[i] << " ";     }      return 0; } 

Output
l n l m p   Rahul Aman Abdul Ram Pradeep   Rahul Aman Fashil Ram Pradeep 

Memory Representation

The advantages of using array of pointer to strings over 2D arrays of characters is that they are space efficient. Consider the following array of pointer to strings:

char* arr[3] = {"Geek", "Geeks", "Geeksfor"}

To store the above strings in 2D array of chars, we have the following statement:

char arr[3][9] = {"Geek", "Geeks", "Geeksfor"}

Now, the below image shows the memory representation of the two arrays. The lighter part is present only in the 2D array.

As we can see, even for the smallest string, the 2D array still have to allocate the same amount of space as that of the largest string. While, this is not the case of array of pointer to string.

Dynamic Array of Pointers to Strings in C++

All the above declarations are static and will be allocated in the heap. We can also create a dynamic array of pointers to strings using the new keyword.

Syntax of Dynamic Array of Pointers to Strings

char** array_name = new char*[size] {initial values....}

In this way, we will create an array of pointer which is stored inside the heap memory. But the strings will still be stored in the read only memory. To store the strings in the dynamic memory, we will have to create a new memory block for each element of this array.

char** array_name = new char*[size];
array_name[i] = new char[strlen("value")];
strcpy(array_name[i], "value");

We can do this for dynamic array of pointer to strings OR...... we can directly use the inbuit containers for dynamic array and strings namely std::vector and std::string where we dont have to worry about size every time we do something.

Example of Dynamic Array of Pointers to String

C++
// C++ Program to illustrate how to create a dynamic array // of pointers to strings #include <cstring> #include <iostream> #include <string> #include <vector>  #define SIZE 3  using namespace std;  // driver code int main() {     // first method to create a dynamic array of pointers to     // strings     char** names1         = new char* [SIZE] { "Geek", "Geeks", "Geeksfor" };      // second method     char** names2 = new char*[SIZE];      // adding elements     names2[0] = new char[strlen("Ram")];     strcpy(names2[0], "Ram");     names2[1] = new char[strlen("Arun")];     strcpy(names2[1], "Arun");     names2[2] = new char[strlen("Vivek")];     strcpy(names2[2], "Vivek");      // using vector and strings     vector<string*> names3;      names3.push_back(new string("Geek"));     names3.push_back(new string("Geeks"));     names3.push_back(new string("Geeksfor"));      // printing all     cout << "First Array: ";     for (int i = 0; i < SIZE; i++) {         cout << names1[i] << " ";     }     cout << endl;     cout << "Second Array: ";     for (int i = 0; i < SIZE; i++) {         cout << names2[i] << " ";     }     cout << endl;     cout << "Last Array: ";     for (int i = 0; i < SIZE; i++) {         cout << *names3[i] << " ";     }      // freeing all memory     delete[] names1;     for (int i = 0; i < SIZE; i++)         delete[] names2[i];     delete[] names2;      // vector of string pointer will be deleted     // automatically      return 0; } 

Output
First Array: Geek Geeks Geeksfor   Second Array: Ram Arun Vivek   Last Array: Geek Geeks Geeksfor 

 


Next Article
Convert String to Char Array in C++

G

gauravggeeksforgeeks
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-string
  • cpp-array
  • cpp-pointer
  • cpp-strings
  • CPP Examples
Practice Tags :
  • CPP
  • cpp-strings

Similar Reads

  • How to Sort an Array of Strings Using Pointers in C++?
    In C++, sorting an array of strings using pointers is quite different from normal sorting because here the manipulation of pointers is done directly, and then according to which string is pointed by the pointer the sorting is done. The task is to sort a given array of strings using pointers. Example
    2 min read
  • 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++. Pointer to Array of String in C++If we are working wit
    2 min read
  • How to Resize an Array of Strings in C++?
    In C++, the array of strings is useful for storing many strings in the same container. Sometimes, we need to change the size of this array. In this article, we will look at how to resize the array of strings in C++. Resize String Array in C++There is no way to directly resize the previously allocate
    2 min read
  • How to Split a String into an Array in C++?
    In C++, splitting a string into an array of substrings means we have to parse the given string based on a delimiter and store each substring in an array. In this article, we will learn how to split a string into an array of substrings in C++. Example: Input: str= “Hello, I am Geek from geeksforgeeks
    2 min read
  • Convert String to Char Array in C++
    In C++, we usually represent text data using the std::string object. But in some cases, we may need to convert a std::string to a character array, the traditional C-style strings. In this article, we will learn how to convert the string to char array in C++. Examples Input: str = "geeksforgeeks"Outp
    4 min read
  • Creating array of pointers in C++
    An array of pointers is an array of pointer variables. It is also known as pointer arrays. We will discuss how to create a 1D and 2D array of pointers dynamically. The word dynamic signifies that the memory is allocated during the runtime, and it allocates memory in Heap Section. In a Stack, memory
    5 min read
  • How to Reverse a String in C++?
    Reversing a string means replacing the first character with the last character, second character with the second last character and so on. In this article, we will learn how to reverse a string in C++. Examples Input: str = "Hello World"Output: dlroW olleHExplanation: The last character is replaced
    2 min read
  • How to Create a Stack of Strings in C++?
    In C++, Stacks are a type of container adaptor with a LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we will learn how to create a stack of strings in C++. Creating a Stack of Strings in C++To crea
    1 min read
  • Take String as Input in C++
    Strings are used to store the textual information. Taking a string as input is a very common operation used in almost all fields of programming. In this article, we will look at different ways to take string as input. The simplest way to take string as the user input is to use cin object. Let's take
    2 min read
  • Array of Linked Lists in C/C++
    An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements that can be accessed randomly using indices of an array.  They can be used to store the collection of primitive data types such as int, float, double, char,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences